├── blitz ├── __init__.py ├── losses │ ├── tests │ │ ├── __init__.py │ │ └── kl_divergence_test.py │ ├── __init__.py │ └── kl_divergence.py ├── modules │ ├── tests │ │ ├── __init__.py │ │ ├── base_bayesian_module_test.py │ │ ├── gru_bayesian_layer_test.py │ │ ├── weight_sampler_test.py │ │ ├── lstm_bayesian_layer_test.py │ │ ├── embadding_bayesian_test.py │ │ ├── linear_bayesian_layer_test.py │ │ └── conv_bayesian_layer_test.py │ ├── __init__.py │ ├── weight_sampler.py │ ├── linear_bayesian_layer.py │ ├── base_bayesian_module.py │ ├── embedding_bayesian_layer.py │ ├── gru_bayesian_layer.py │ ├── lstm_bayesian_layer.py │ └── conv_bayesian_layer.py ├── utils │ ├── tests │ │ ├── __init__.py │ │ ├── layer_wrappers_test.py │ │ └── variational_estimator_test.py │ ├── __init__.py │ ├── minibatch_weighting.py │ ├── layer_wrappers.py │ └── variational_estimator.py ├── models │ ├── __init__.py │ └── b_vgg.py ├── examples │ ├── requirements_stocks_example.txt │ ├── bayesian_LeNet_mnist.py │ ├── bayesian_regression_boston.py │ └── cifar10_bvgg.py └── run_tests.sh ├── requirements.txt ├── doc ├── losses.md ├── samplers.md ├── utils.md └── layers.md ├── .github ├── FUNDING.yml └── workflows │ ├── pythonapp.yml │ └── pythonpublish.yml ├── setup.py ├── .gitignore ├── README.md └── LICENSE /blitz/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /blitz/losses/tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /blitz/modules/tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /blitz/utils/tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /blitz/models/__init__.py: -------------------------------------------------------------------------------- 1 | from .b_vgg import * -------------------------------------------------------------------------------- /blitz/losses/__init__.py: -------------------------------------------------------------------------------- 1 | from .kl_divergence import * -------------------------------------------------------------------------------- /blitz/examples/requirements_stocks_example.txt: -------------------------------------------------------------------------------- 1 | pandas 2 | numpy 3 | sklearn 4 | matplotlib -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | torch>=1.7.0 2 | torchvision>=0.5.0 3 | numpy 4 | scikit-learn>=0.22.2 5 | pillow>=7.1 6 | -------------------------------------------------------------------------------- /blitz/utils/__init__.py: -------------------------------------------------------------------------------- 1 | from .variational_estimator import variational_estimator 2 | from .layer_wrappers import Flipout, Radial 3 | -------------------------------------------------------------------------------- /blitz/run_tests.sh: -------------------------------------------------------------------------------- 1 | eval "$(conda shell.bash hook)" 2 | conda activate blitz; 3 | pip install ../.; 4 | python -m unittest discover -p '*_test.py' -s '.' 5 | -------------------------------------------------------------------------------- /blitz/modules/__init__.py: -------------------------------------------------------------------------------- 1 | from .linear_bayesian_layer import * 2 | from .conv_bayesian_layer import * 3 | from .lstm_bayesian_layer import * 4 | from .gru_bayesian_layer import * 5 | from .embedding_bayesian_layer import * 6 | from .weight_sampler import * -------------------------------------------------------------------------------- /doc/losses.md: -------------------------------------------------------------------------------- 1 | # Losses 2 | 3 | # Index: 4 | * [KL Divergence from nn](#KL-Divergence-from-nn) 5 | 6 | --- 7 | 8 | ## KL Divergence from nn 9 | ### blitz.losses.kl_divergence_from_nn(model) 10 | Returns the summed KL Divergence of each of the models bayesian layers. 11 | #### Parameters: 12 | * model - torch.nn.Module 13 | --- 14 | -------------------------------------------------------------------------------- /blitz/losses/kl_divergence.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn 3 | import torch.nn.functional as F 4 | 5 | from blitz.modules.base_bayesian_module import BayesianModule 6 | 7 | def kl_divergence_from_nn(model): 8 | 9 | """ 10 | Gathers the KL Divergence from a nn.Module object 11 | Works by gathering each Bayesian layer kl divergence and summing it, doing nothing with the non Bayesian ones 12 | """ 13 | kl_divergence = 0 14 | for module in model.modules(): 15 | if isinstance(module, (BayesianModule)): 16 | kl_divergence += module.log_variational_posterior - module.log_prior 17 | return kl_divergence 18 | 19 | -------------------------------------------------------------------------------- /blitz/utils/minibatch_weighting.py: -------------------------------------------------------------------------------- 1 | def minibatch_weight(batch_idx, num_batches): 2 | 3 | """Calculates the minibatch weight. 4 | 5 | A formula for calculating the minibatch weight is described in 6 | section 3.4 of the 'Weight Uncertainty in Neural Networks' paper. 7 | The weighting decreases as the batch index increases, this is 8 | because the the first few batches are influenced heavily by 9 | the complexity cost. 10 | 11 | Parameters: 12 | batch_idx: int -> the current batch index (from 0 to num_batches-1) 13 | num_batches: int -> the total number of batches 14 | """ 15 | 16 | return 2 ** (num_batches - batch_idx - 1) / (2 ** num_batches - 1) 17 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] 4 | patreon: # Replace with a single Patreon username 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | custom: 'https://www.buymeacoffee.com/piEsposito' 13 | -------------------------------------------------------------------------------- /.github/workflows/pythonapp.yml: -------------------------------------------------------------------------------- 1 | # This workflow will install Python dependencies, run tests and lint with a single version of Python 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions 3 | 4 | name: Run tests 5 | 6 | on: 7 | push: 8 | branches: [ master ] 9 | pull_request: 10 | branches: [ master ] 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - uses: actions/checkout@v2 19 | - name: Set up Python 3.8 20 | uses: actions/setup-python@v2 21 | with: 22 | python-version: 3.8 23 | - name: Install dependencies 24 | run: | 25 | python -m pip install --upgrade pip 26 | if [ -f requirements.txt ]; then pip install -r requirements.txt; fi 27 | - name: Test with unittest 28 | run: | 29 | python -m unittest discover -p '*_test.py' -s '.' 30 | -------------------------------------------------------------------------------- /.github/workflows/pythonpublish.yml: -------------------------------------------------------------------------------- 1 | # This workflows will upload a Python Package using Twine when a release is created 2 | # For more information see: https://help.github.com/en/actions/language-and-framework-guides/using-python-with-github-actions#publishing-to-package-registries 3 | 4 | name: Upload Python Package 5 | 6 | on: 7 | release: 8 | types: [created] 9 | 10 | jobs: 11 | deploy: 12 | 13 | runs-on: ubuntu-latest 14 | 15 | steps: 16 | - uses: actions/checkout@v2 17 | - name: Set up Python 18 | uses: actions/setup-python@v2 19 | with: 20 | python-version: '3.x' 21 | - name: Install dependencies 22 | run: | 23 | python -m pip install --upgrade pip 24 | pip install setuptools wheel twine 25 | - name: Build and publish 26 | env: 27 | TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }} 28 | TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }} 29 | run: | 30 | python setup.py sdist bdist_wheel 31 | twine upload dist/* 32 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | from os import path 3 | 4 | this_directory = path.abspath(path.dirname(__file__)) 5 | with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f: 6 | long_desc = f.read() 7 | 8 | with open(path.join(this_directory, 'requirements.txt'), encoding='utf-8') as f: 9 | install_requires = f.read() 10 | 11 | setup( 12 | name = "blitz-bayesian-pytorch", 13 | packages = find_packages(), 14 | version = "0.2.8", 15 | description = "A simple and extensible library to create Bayesian Neural Network Layers on PyTorch without trouble and with full integration with nn.Module and nn.Sequential.", 16 | author = "Pi Esposito", 17 | url = "https://github.com/piEsposito/blitz-bayesian-deep-learning", 18 | long_description = long_desc, 19 | long_description_content_type = "text/markdown", 20 | install_requires = install_requires, 21 | classifiers = [ 22 | "Development Status :: 3 - Alpha", 23 | "Intended Audience :: Developers", 24 | "Programming Language :: Python :: 3.7" 25 | ] 26 | ) 27 | -------------------------------------------------------------------------------- /blitz/losses/tests/kl_divergence_test.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import torch 3 | import torch.nn as nn 4 | import torch.nn.functional as F 5 | 6 | from blitz.losses import kl_divergence_from_nn 7 | from blitz.modules import BayesianLinear, BayesianConv2d 8 | 9 | class TestKLDivergence(unittest.TestCase): 10 | 11 | def test_kl_divergence_bayesian_linear_module(self): 12 | blinear = BayesianLinear(10, 10) 13 | to_feed = torch.ones((1, 10)) 14 | predicted = blinear(to_feed) 15 | 16 | complexity_cost = blinear.log_variational_posterior - blinear.log_prior 17 | kl_complexity_cost = kl_divergence_from_nn(blinear) 18 | 19 | self.assertEqual((complexity_cost == kl_complexity_cost).all(), torch.tensor(True)) 20 | pass 21 | 22 | def test_kl_divergence_bayesian_conv2d_module(self): 23 | bconv = BayesianConv2d(in_channels=3, 24 | out_channels=3, 25 | kernel_size=(3,3)) 26 | 27 | to_feed = torch.ones((1, 3, 25, 25)) 28 | predicted = bconv(to_feed) 29 | 30 | complexity_cost = bconv.log_variational_posterior - bconv.log_prior 31 | kl_complexity_cost = kl_divergence_from_nn(bconv) 32 | 33 | self.assertEqual((complexity_cost == kl_complexity_cost).all(), torch.tensor(True)) 34 | pass 35 | 36 | def test_kl_divergence_non_bayesian_module(self): 37 | linear = nn.Linear(10, 10) 38 | to_feed = torch.ones((1, 10)) 39 | predicted = linear(to_feed) 40 | 41 | kl_complexity_cost = kl_divergence_from_nn(linear) 42 | self.assertEqual((torch.tensor(0) == kl_complexity_cost).all(), torch.tensor(True)) 43 | pass 44 | 45 | if __name__ == "__main__": 46 | unittest.main() -------------------------------------------------------------------------------- /blitz/utils/tests/layer_wrappers_test.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | import torch 4 | 5 | from blitz.modules import BayesianLinear, BayesianLSTM 6 | from blitz.utils import Flipout, Radial 7 | 8 | 9 | class TestFlipout(unittest.TestCase): 10 | 11 | def test_linear(self): 12 | layer = Flipout(BayesianLinear)(10, 10) 13 | in_ = torch.ones(2, 10) 14 | out_ = layer(in_) 15 | # print(out_) 16 | self.assertEqual((out_[0, :] != out_[1, :]).any(), torch.tensor(True)) 17 | 18 | def test_RNN(self): 19 | layer = Flipout(BayesianLSTM)(10, 10) 20 | in_ = torch.ones(2, 3, 10) 21 | out_, _ = layer(in_) 22 | # print(out_) 23 | self.assertEqual((out_[0, :, :] != out_[1, :, :]).any(), torch.tensor(True)) 24 | 25 | 26 | class TestRadial(unittest.TestCase): 27 | 28 | def test_linear(self): 29 | layer = Radial(BayesianLinear)(10, 10) 30 | in_ = torch.ones(2, 10) 31 | out_ = layer(in_) 32 | # print(out_) 33 | 34 | def test_RNN(self): 35 | layer = Radial(BayesianLSTM)(10, 10) 36 | in_ = torch.ones(2, 3, 10) 37 | out_, _ = layer(in_) 38 | # print(out_) 39 | 40 | 41 | class TestNested(unittest.TestCase): 42 | 43 | def test_linear(self): 44 | layer = Radial(Flipout(BayesianLinear)(10, 10)) 45 | in_ = torch.ones(2, 10) 46 | out_ = layer(in_) 47 | # print(out_) 48 | self.assertEqual((out_[0, :] != out_[1, :]).any(), torch.tensor(True)) 49 | 50 | def test_RNN(self): 51 | layer = Radial(Flipout(BayesianLSTM)(10, 10)) 52 | in_ = torch.ones(2, 3, 10) 53 | out_, _ = layer(in_) 54 | # print(out_) 55 | self.assertEqual((out_[0, :, :] != out_[1, :, :]).any(), torch.tensor(True)) 56 | 57 | 58 | if __name__ == "__main__": 59 | unittest.main() 60 | -------------------------------------------------------------------------------- /blitz/modules/tests/base_bayesian_module_test.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import torch 3 | from torch import nn 4 | 5 | from blitz.modules.base_bayesian_module import BayesianModule, BayesianRNN 6 | from blitz.modules import BayesianLSTM, BayesianGRU 7 | 8 | class TestLinearBayesian(unittest.TestCase): 9 | 10 | def test_init_bayesian_layer(self): 11 | b_module = BayesianModule() 12 | self.assertEqual(isinstance(b_module, (nn.Module)), True) 13 | 14 | def test_init_brnn(self): 15 | b_module = BayesianRNN() 16 | self.assertEqual(isinstance(b_module, (nn.Module)), True) 17 | 18 | def test_brnn_sharpen_posterior_lstm(self): 19 | b_module = BayesianLSTM(3, 5, sharpen=True) 20 | in_tensor = torch.ones(5, 4, 3) 21 | out_tensor = b_module(in_tensor)[0][:, -1, :] 22 | 23 | loss = nn.MSELoss()(out_tensor.clone().detach().normal_(), out_tensor) 24 | b_module.sharpen_posterior(loss, in_tensor.shape) 25 | 26 | def test_brnn_sharpen_posterior_on_forward_lstm(self): 27 | b_module = BayesianLSTM(3, 5, sharpen=True) 28 | in_tensor = torch.ones(5, 4, 3) 29 | out_tensor = b_module(in_tensor)[0][:, -1, :] 30 | 31 | loss = nn.MSELoss()(out_tensor.clone().detach().normal_(), out_tensor) 32 | b_module.forward(in_tensor, sharpen_loss=loss) 33 | 34 | def test_brnn_sharpen_posterior_gru(self): 35 | b_module = BayesianGRU(3, 5, sharpen=True) 36 | in_tensor = torch.ones(5, 4, 3) 37 | out_tensor = b_module(in_tensor)[0][:, -1, :] 38 | 39 | loss = nn.MSELoss()(out_tensor.clone().detach().normal_(), out_tensor) 40 | b_module.sharpen_posterior(loss, in_tensor.shape) 41 | 42 | def test_brnn_sharpen_posterior_on_forward_gru(self): 43 | b_module = BayesianGRU(3, 5, sharpen=True) 44 | in_tensor = torch.ones(5, 4, 3) 45 | out_tensor = b_module(in_tensor)[0][:, -1, :] 46 | 47 | loss = nn.MSELoss()(out_tensor.clone().detach().normal_(), out_tensor) 48 | b_module.forward(in_tensor, sharpen_loss=loss) 49 | 50 | if __name__ == "__main__": 51 | unittest.main() -------------------------------------------------------------------------------- /doc/samplers.md: -------------------------------------------------------------------------------- 1 | # Weight a priori and a posteriori sampler 2 | 3 | # Index: 4 | * [TrainableRandomDistribution](#class-TrainableRandomDistribution) 5 | * [PriorWeightDistribution](#class-PriorWeightDistribution) 6 | 7 | --- 8 | ## class TrainableRandomDistribution 9 | ### blitz.modules.weight_sampler.TrainableRandomDistribution(mu, rho) 10 | Creates a weight sampler in order to introduce uncertainity on the layers weights. 11 | #### Parameters: 12 | * mu - torch.tensor with two or more dimensions: mu parameter of the Gaussian weight sampler proposed on Bayes by Backprop paper 13 | * rho - torch.tensor with two or more dimensions: rho parameter of the Gaussian weight sampler proposed on Bayes by Backprop paper 14 | 15 | #### Methods: 16 | * sample(): 17 | 18 | Returns a torch.tensor corresponding to the sampled weights of the layer. Also stores the current distribution sigma and weights internally for further use. 19 | * log_posterior(): 20 | 21 | Returns the torch.tensor corresponding to the summed log-likelihood of the sampled weights given its mu and sigma parameters, considering it follows a Gaussian distribution. 22 | 23 | --- 24 | 25 | ## class PriorWeightDistribution 26 | ### blitz.modules.weight_sampler.PriorWeightDistribution(pi, sigma1, sigma2) 27 | Creates a log-likelihood calculator for any matrix w passed on the log_prior method, considering a Scaled Gaussian Mixture model of N(0, sigma1) with weight pi (parameter) and N(0, sigma2) with weight (1-pi) parameter, for each distribution, following the idea on Bayes by Backprop paper. 28 | #### Parameters: 29 | * pi - float corresponding to a factor for scaling the mixture models; AND 30 | * sigma1 - float corresponding to the standard deviation for the first Gaussian Model of the mixture; AND 31 | * sigma2 - float corresponding to the standard deviation for the second Gaussian Model of the mixture; OR 32 | 33 | * dist - torch.distributions.distribution.Distribution corresponding to a prior distribution different than a normal / scale mixture normal; if you pass that, the prior distribution will be that one and sigma1 and sigma2 and pi can be dismissed. - Note that there is a torch issue that may output you logprob as NaN, so beware of the prior dist you are using. 34 | 35 | #### Methods: 36 | * log_prior(w): 37 | 38 | Returns the torch.tensor corresponding to the summed log-likelihood of the matrix of weights "w" given PriorWeightDistribution object scaled Gaussian Mixture model parameters. 39 | ##### Parameters: 40 | * w - torch.tensor 41 | --- 42 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Jetbrains project settings 118 | .idea/ 119 | 120 | # Rope project settings 121 | .ropeproject 122 | 123 | # mkdocs documentation 124 | /site 125 | 126 | # mypy 127 | .mypy_cache/ 128 | .dmypy.json 129 | dmypy.json 130 | 131 | # Pyre type checker 132 | .pyre/ 133 | 134 | #vscode 135 | .vscode/ 136 | 137 | #example data 138 | example/data/ 139 | utils/data/ 140 | *data/ 141 | /data/ -------------------------------------------------------------------------------- /doc/utils.md: -------------------------------------------------------------------------------- 1 | # Utils and decorators to enable easy basyesian training and inference 2 | 3 | # Index: 4 | * [Decorator variational_estimator](#Variational-Estimator) 5 | --- 6 | ## Variational Estimator 7 | 8 | Dynamically adds some util methods to object that inherits from torch.nn.Module in order to facilitate bayesian training and inference. 9 | 10 | ### @variational_estimator(model) 11 | #### Parameters: 12 | * model: -> torch.nn.Module to have introduced the Bayesian DL methods 13 | 14 | ### Methods introduced: 15 | * #### nn_kl_divergence() 16 | 17 | Returns torch.tensor corresponding to the summed KL divergence (relative to the curren weight sampling) of all of its BayesianModule layers. 18 | 19 | * #### freeze_model() 20 | 21 | Freezes the model weights by making its BayesianModule layers forward operation use, while not unfrozen, only its weight distribution mean tensor. 22 | 23 | * #### unfreeze_model() 24 | 25 | Unfreezes the model by letting it sample its weights using the Bayes By Backprop paper proposed algorithm rather than using only its expected value. 26 | 27 | * #### sample_elbo(inputs, labels, criterion, sample_nbr) 28 | 29 | Samples the ELBO loss of the model sample_nbr times by doing feedforward operations and summing its model kl divergence with the loss the criterion outputs. 30 | 31 | ##### Parameters: 32 | * inputs: torch.tensor -> the input data to the model 33 | * labels: torch.tensor -> label data for the performance-part of the loss calculation 34 | 35 | The shape of the labels must match the label-parameter shape of the criterion (one hot encoded or as index, if needed) 36 | 37 | * criterion: torch.nn.Module, custom criterion (loss) function, torch.nn.functional function -> criterion to gather the performance cost for the model 38 | * sample_nbr: int -> The number of times of the weight-sampling and predictions done in our Monte-Carlo approach to gather the loss to be .backwarded in the optimization of the model. 39 | 40 | #### Returns: 41 | * loss: torch.tensor -> elbo loss for the data given 42 | 43 | * #### mfvi_forward(inputs, sample_nbr) 44 | 45 | Performs mean-field variational inference for the variational estimator model on the inputs 46 | 47 | #### Parameters: 48 | * inputs: torch.tensor -> the input data to the model 49 | * sample_nbr: int -> number of forward passes to be done on the data 50 | #### Returns: 51 | * mean_: torch.tensor -> mean of the perdictions along each of the features of each datapoint on the batch axis, for each feature of ea 52 | * std_: torch.tensor -> std of the predictions along each of the features of each datapoint on the batch axis 53 | 54 | -------------------------------------------------------------------------------- /blitz/modules/tests/gru_bayesian_layer_test.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import torch 3 | from torch import nn 4 | 5 | from blitz.modules import BayesianGRU 6 | from blitz.modules.base_bayesian_module import BayesianModule 7 | 8 | class TestLinearBayesian(unittest.TestCase): 9 | def test_init_bayesian_GRU(self): 10 | b_GRU = BayesianGRU(10, 10) 11 | self.assertEqual(isinstance(b_GRU, (nn.Module)), True) 12 | self.assertEqual(isinstance(b_GRU, (BayesianModule)), True) 13 | pass 14 | 15 | def test_infer_shape_1_sample(self): 16 | deterministic_GRU = nn.GRU(1, 10, 1, batch_first=True) 17 | in_data = torch.ones((10, 10, 1)) 18 | det_inference = deterministic_GRU(in_data) 19 | 20 | b_GRU = BayesianGRU(1, 10) 21 | b_inference = b_GRU(in_data, hidden_states=None) 22 | 23 | self.assertEqual(det_inference[0].shape, b_inference[0].shape) 24 | pass 25 | 26 | def test_variational_inference(self): 27 | #create module, check if inference is variating 28 | deterministic_GRU = nn.GRU(1, 10, 1, batch_first=True) 29 | in_data = torch.ones((10, 10, 1)) 30 | det_inference = deterministic_GRU(in_data) 31 | 32 | b_GRU = BayesianGRU(1, 10) 33 | b_inference_1 = b_GRU(in_data, hidden_states=None) 34 | b_inference_2 = b_GRU(in_data, hidden_states=None) 35 | 36 | self.assertEqual((b_inference_1[0] != b_inference_2[0]).any(), torch.tensor(True)) 37 | self.assertEqual((det_inference[0] == det_inference[0]).all(), torch.tensor(True)) 38 | pass 39 | 40 | def test_frozen_inference(self): 41 | b_GRU = BayesianGRU(1, 10) 42 | b_GRU.freeze = True 43 | 44 | in_data = torch.ones((10, 10, 1)) 45 | b_inference_1 = b_GRU(in_data, hidden_states=None) 46 | b_inference_2 = b_GRU(in_data, hidden_states=None) 47 | 48 | self.assertEqual((b_inference_1[0] == b_inference_2[0]).all(), torch.tensor(True)) 49 | 50 | def test_kl_divergence(self): 51 | #create model, sample weights 52 | #check if kl divergence between apriori and a posteriori is working 53 | b_GRU = BayesianGRU(1, 10) 54 | to_feed = torch.ones((10, 10, 1)) 55 | 56 | predicted = b_GRU(to_feed) 57 | complexity_cost = b_GRU.log_variational_posterior - b_GRU.log_prior 58 | 59 | self.assertEqual((complexity_cost == complexity_cost).all(), torch.tensor(True)) 60 | 61 | def test_sequential_cuda(self): 62 | #check if we can create sequential models chaning our Bayesian Linear layers 63 | device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') 64 | b_GRU = BayesianGRU(1, 10) 65 | to_feed = torch.ones((10, 10, 1)) 66 | 67 | predicted = b_GRU(to_feed) 68 | 69 | 70 | 71 | if __name__ == "__main__": 72 | unittest.main() -------------------------------------------------------------------------------- /blitz/modules/tests/weight_sampler_test.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import torch 3 | from blitz.modules.weight_sampler import TrainableRandomDistribution, PriorWeightDistribution 4 | from blitz.modules import BayesianLinear 5 | 6 | class TestWeightSampler(unittest.TestCase): 7 | 8 | def test_gaussian_sample(self): 9 | #checks if sample works 10 | 11 | mu = torch.Tensor(10, 10).uniform_(-1, 1) 12 | rho = torch.Tensor(10, 10).uniform_(-1, 1) 13 | 14 | dist = TrainableRandomDistribution(mu, rho) 15 | s1 = dist.sample() 16 | s2 = dist.sample() 17 | 18 | self.assertEqual((s1 != s2).any(), torch.tensor(True)) 19 | self.assertEqual(mu.shape, s1.shape) 20 | self.assertEqual(rho.shape, s1.shape) 21 | pass 22 | 23 | def test_gaussian_log_posterior(self): 24 | #checks if it the log_posterior calculator is working 25 | 26 | mu = torch.Tensor(10, 10).uniform_(-1, 1) 27 | rho = torch.Tensor(10, 10).uniform_(-1, 1) 28 | 29 | dist = TrainableRandomDistribution(mu, rho) 30 | s1 = dist.sample() 31 | 32 | log_posterior = dist.log_posterior() 33 | #check if it is not none 34 | self.assertEqual(log_posterior == log_posterior, torch.tensor(True)) 35 | 36 | def test_scale_mixture_prior(self): 37 | mu = torch.Tensor(10, 10).uniform_(-1, 1) 38 | rho = torch.Tensor(10, 10).uniform_(-1, 1) 39 | 40 | dist = TrainableRandomDistribution(mu, rho) 41 | s1 = dist.sample() 42 | 43 | log_posterior = dist.log_posterior() 44 | 45 | prior_dist = PriorWeightDistribution(0.5, 1, .002) 46 | log_prior = prior_dist.log_prior(s1) 47 | 48 | #print(log_prior) 49 | #print(log_posterior) 50 | self.assertEqual(log_prior == log_prior, torch.tensor(True)) 51 | self.assertEqual(log_posterior <= log_posterior - log_prior, torch.tensor(True)) 52 | pass 53 | 54 | def test_scale_mixture_any_prior(self): 55 | mu = torch.Tensor(10, 10).uniform_(-1, 1) 56 | rho = torch.Tensor(10, 10).uniform_(-1, 1) 57 | 58 | dist = TrainableRandomDistribution(mu, rho) 59 | s1 = dist.sample() 60 | 61 | log_posterior = dist.log_posterior() 62 | 63 | prior_dist = PriorWeightDistribution(dist=torch.distributions.studentT.StudentT(1, 1)) 64 | log_prior = prior_dist.log_prior(s1) 65 | 66 | #print(log_prior) 67 | #print(log_posterior) 68 | self.assertEqual(log_prior == log_prior, torch.tensor(True)) 69 | self.assertEqual(log_posterior <= log_posterior - log_prior, torch.tensor(True)) 70 | pass 71 | 72 | def test_any_prior_on_layer(self): 73 | l = BayesianLinear(7, 5, prior_dist=torch.distributions.studentT.StudentT(1, 1)) 74 | t = torch.ones(3, 7) 75 | _ = l(t) 76 | 77 | self.assertEqual(l.log_prior, l.log_prior) 78 | pass 79 | 80 | if __name__ == "__main__": 81 | unittest.main() -------------------------------------------------------------------------------- /blitz/modules/tests/lstm_bayesian_layer_test.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import torch 3 | from torch import nn 4 | 5 | from blitz.modules import BayesianLSTM 6 | from blitz.modules.base_bayesian_module import BayesianModule 7 | 8 | class TestLinearBayesian(unittest.TestCase): 9 | def test_init_bayesian_lstm(self): 10 | b_lstm = BayesianLSTM(10, 10) 11 | self.assertEqual(isinstance(b_lstm, (nn.Module)), True) 12 | self.assertEqual(isinstance(b_lstm, (BayesianModule)), True) 13 | pass 14 | 15 | def test_infer_shape_1_sample(self): 16 | deterministic_lstm = nn.LSTM(1, 10, 1, batch_first=True) 17 | in_data = torch.ones((10, 10, 1)) 18 | det_inference = deterministic_lstm(in_data) 19 | 20 | b_lstm = BayesianLSTM(1, 10) 21 | b_inference = b_lstm(in_data, hidden_states=None) 22 | 23 | self.assertEqual(det_inference[0].shape, b_inference[0].shape) 24 | pass 25 | 26 | def test_variational_inference(self): 27 | #create module, check if inference is variating 28 | deterministic_lstm = nn.LSTM(1, 10, 1, batch_first=True) 29 | in_data = torch.ones((10, 10, 1)) 30 | det_inference = deterministic_lstm(in_data) 31 | 32 | b_lstm = BayesianLSTM(1, 10) 33 | b_inference_1 = b_lstm(in_data, hidden_states=None) 34 | b_inference_2 = b_lstm(in_data, hidden_states=None) 35 | 36 | self.assertEqual((b_inference_1[0] != b_inference_2[0]).any(), torch.tensor(True)) 37 | self.assertEqual((det_inference[0] == det_inference[0]).all(), torch.tensor(True)) 38 | pass 39 | 40 | def test_frozen_inference(self): 41 | b_lstm = BayesianLSTM(1, 10) 42 | b_lstm.freeze = True 43 | 44 | in_data = torch.ones((10, 10, 1)) 45 | b_inference_1 = b_lstm(in_data, hidden_states=None) 46 | b_inference_2 = b_lstm(in_data, hidden_states=None) 47 | 48 | self.assertEqual((b_inference_1[0] == b_inference_2[0]).all(), torch.tensor(True)) 49 | 50 | def test_peephole_inference(self): 51 | b_lstm = BayesianLSTM(1, 10, peephole=True) 52 | in_data = torch.ones((10, 10, 1)) 53 | b_lstm(in_data) 54 | b_lstm.freeze = True 55 | b_lstm(in_data) 56 | 57 | def test_kl_divergence(self): 58 | #create model, sample weights 59 | #check if kl divergence between apriori and a posteriori is working 60 | b_lstm = BayesianLSTM(1, 10) 61 | to_feed = torch.ones((10, 10, 1)) 62 | 63 | predicted = b_lstm(to_feed) 64 | complexity_cost = b_lstm.log_variational_posterior - b_lstm.log_prior 65 | 66 | self.assertEqual((complexity_cost == complexity_cost).all(), torch.tensor(True)) 67 | 68 | def test_sequential_cuda(self): 69 | #check if we can create sequential models chaning our Bayesian Linear layers 70 | device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') 71 | b_lstm = BayesianLSTM(1, 10) 72 | to_feed = torch.ones((10, 10, 1)) 73 | 74 | predicted = b_lstm(to_feed) 75 | 76 | 77 | 78 | if __name__ == "__main__": 79 | unittest.main() -------------------------------------------------------------------------------- /blitz/examples/bayesian_LeNet_mnist.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | import torch.optim as optim 5 | import torchvision.datasets as dsets 6 | import torchvision.transforms as transforms 7 | 8 | from blitz.modules import BayesianLinear, BayesianConv2d 9 | from blitz.losses import kl_divergence_from_nn 10 | from blitz.utils import variational_estimator 11 | 12 | train_dataset = dsets.MNIST(root="./data", 13 | train=True, 14 | transform=transforms.ToTensor(), 15 | download=True 16 | ) 17 | train_loader = torch.utils.data.DataLoader(dataset=train_dataset, 18 | batch_size=64, 19 | shuffle=True) 20 | 21 | test_dataset = dsets.MNIST(root="./data", 22 | train=False, 23 | transform=transforms.ToTensor(), 24 | download=True 25 | ) 26 | test_loader = torch.utils.data.DataLoader(dataset=test_dataset, 27 | batch_size=64, 28 | shuffle=True) 29 | 30 | @variational_estimator 31 | class BayesianCNN(nn.Module): 32 | def __init__(self): 33 | super().__init__() 34 | self.conv1 = BayesianConv2d(1, 6, (5,5)) 35 | self.conv2 = BayesianConv2d(6, 16, (5,5)) 36 | self.fc1 = BayesianLinear(256, 120) 37 | self.fc2 = BayesianLinear(120, 84) 38 | self.fc3 = BayesianLinear(84, 10) 39 | 40 | def forward(self, x): 41 | out = F.relu(self.conv1(x)) 42 | out = F.max_pool2d(out, 2) 43 | out = F.relu(self.conv2(out)) 44 | out = F.max_pool2d(out, 2) 45 | out = out.view(out.size(0), -1) 46 | out = F.relu(self.fc1(out)) 47 | out = F.relu(self.fc2(out)) 48 | out = self.fc3(out) 49 | return out 50 | 51 | device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') 52 | classifier = BayesianCNN().to(device) 53 | optimizer = optim.Adam(classifier.parameters(), lr=0.001) 54 | criterion = torch.nn.CrossEntropyLoss() 55 | 56 | iteration = 0 57 | for epoch in range(100): 58 | for i, (datapoints, labels) in enumerate(train_loader): 59 | optimizer.zero_grad() 60 | loss = classifier.sample_elbo(inputs=datapoints.to(device), 61 | labels=labels.to(device), 62 | criterion=criterion, 63 | sample_nbr=3, 64 | complexity_cost_weight=1/50000) 65 | #print(loss) 66 | loss.backward() 67 | optimizer.step() 68 | 69 | iteration += 1 70 | if iteration%250==0: 71 | print(loss) 72 | correct = 0 73 | total = 0 74 | with torch.no_grad(): 75 | for data in test_loader: 76 | images, labels = data 77 | outputs = classifier(images.to(device)) 78 | _, predicted = torch.max(outputs.data, 1) 79 | total += labels.size(0) 80 | correct += (predicted == labels.to(device)).sum().item() 81 | print('Iteration: {} | Accuracy of the network on the 10000 test images: {} %'.format(str(iteration) ,str(100 * correct / total))) -------------------------------------------------------------------------------- /blitz/modules/weight_sampler.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import numpy as np 3 | import torch.nn as nn 4 | import torch.functional as F 5 | 6 | class TrainableRandomDistribution(nn.Module): 7 | #Samples weights for variational inference as in Weights Uncertainity on Neural Networks (Bayes by backprop paper) 8 | #Calculates the variational posterior part of the complexity part of the loss 9 | def __init__(self, mu, rho): 10 | super().__init__() 11 | 12 | self.mu = nn.Parameter(mu) 13 | self.rho = nn.Parameter(rho) 14 | self.register_buffer('eps_w', torch.Tensor(self.mu.shape)) 15 | self.sigma = None 16 | self.w = None 17 | self.pi = np.pi 18 | #self.normal = torch.distributions.Normal(0, 1) 19 | 20 | def sample(self): 21 | """ 22 | Samples weights by sampling form a Normal distribution, multiplying by a sigma, which is 23 | a function from a trainable parameter, and adding a mean 24 | 25 | sets those weights as the current ones 26 | 27 | returns: 28 | torch.tensor with same shape as self.mu and self.rho 29 | """ 30 | 31 | self.eps_w.data.normal_() 32 | self.sigma = torch.log1p(torch.exp(self.rho)) 33 | self.w = self.mu + self.sigma * self.eps_w 34 | return self.w 35 | 36 | def log_posterior(self, w=None): 37 | 38 | """ 39 | Calculates the log_likelihood for each of the weights sampled as a part of the complexity cost 40 | 41 | returns: 42 | torch.tensor with shape [] 43 | """ 44 | 45 | assert (self.w is not None), "You can only have a log posterior for W if you've already sampled it" 46 | if w is None: 47 | w = self.w 48 | 49 | log_sqrt2pi = np.log(np.sqrt(2*self.pi)) 50 | log_posteriors = -log_sqrt2pi - torch.log(self.sigma) - (((w - self.mu) ** 2)/(2 * self.sigma ** 2)) - 0.5 51 | return log_posteriors.sum() 52 | 53 | class PriorWeightDistribution(nn.Module): 54 | #Calculates a Scale Mixture Prior distribution for the prior part of the complexity cost on Bayes by Backprop paper 55 | def __init__(self, 56 | pi=1, 57 | sigma1=0.1, 58 | sigma2=0.001, 59 | dist=None): 60 | super().__init__() 61 | 62 | 63 | if (dist is None): 64 | self.pi = pi 65 | self.sigma1 = sigma1 66 | self.sigma2 = sigma2 67 | self.dist1 = torch.distributions.Normal(0, sigma1) 68 | self.dist2 = torch.distributions.Normal(0, sigma2) 69 | 70 | if (dist is not None): 71 | self.pi = 1 72 | self.dist1 = dist 73 | self.dist2 = None 74 | 75 | 76 | 77 | def log_prior(self, w): 78 | """ 79 | Calculates the log_likelihood for each of the weights sampled relative to a prior distribution as a part of the complexity cost 80 | 81 | returns: 82 | torch.tensor with shape [] 83 | """ 84 | prob_n1 = torch.exp(self.dist1.log_prob(w)) 85 | 86 | if self.dist2 is not None: 87 | prob_n2 = torch.exp(self.dist2.log_prob(w)) 88 | if self.dist2 is None: 89 | prob_n2 = 0 90 | 91 | # Prior of the mixture distribution, adding 1e-6 prevents numeric problems with log(p) for small p 92 | prior_pdf = (self.pi * prob_n1 + (1 - self.pi) * prob_n2) + 1e-6 93 | 94 | return (torch.log(prior_pdf) - 0.5).sum() 95 | -------------------------------------------------------------------------------- /blitz/models/b_vgg.py: -------------------------------------------------------------------------------- 1 | 2 | import math 3 | 4 | import torch.nn as nn 5 | import torch.nn.init as init 6 | from blitz.modules import BayesianLinear, BayesianConv2d 7 | from blitz.utils import variational_estimator 8 | 9 | __all__ = [ 10 | 'VGG', 'vgg11', 'vgg11_bn', 'vgg13', 'vgg13_bn', 'vgg16', 'vgg16_bn', 11 | 'vgg19_bn', 'vgg19', 12 | ] 13 | 14 | @variational_estimator 15 | class VGG(nn.Module): 16 | ''' 17 | VGG model 18 | ''' 19 | def __init__(self, features, out_nodes=10): 20 | super(VGG, self).__init__() 21 | self.features = features 22 | self.classifier = nn.Sequential( 23 | #nn.Dropout(), 24 | BayesianLinear(512, 512), 25 | nn.ReLU(True), 26 | #nn.Dropout(), 27 | BayesianLinear(512, 512), 28 | nn.ReLU(True), 29 | BayesianLinear(512, out_nodes), 30 | ) 31 | 32 | for m in self.modules(): 33 | if isinstance(m, BayesianConv2d): 34 | n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels 35 | m.weight_mu.data.normal_(0, math.sqrt(2. / n)) 36 | m.bias_mu.data.zero_() 37 | 38 | 39 | def forward(self, x): 40 | x = self.features(x) 41 | x = x.view(x.size(0), -1) 42 | x = self.classifier(x) 43 | return x 44 | 45 | 46 | def make_layers(cfg, batch_norm=False): 47 | layers = [] 48 | in_channels = 3 49 | for v in cfg: 50 | if v == 'M': 51 | layers += [nn.MaxPool2d(kernel_size=2, stride=2)] 52 | else: 53 | conv2d = BayesianConv2d(in_channels, v, kernel_size=(3, 3), padding=1, bias=True) 54 | if batch_norm: 55 | layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=True)] 56 | else: 57 | layers += [conv2d, nn.ReLU(inplace=True)] 58 | in_channels = v 59 | return nn.Sequential(*layers) 60 | 61 | 62 | cfg = { 63 | 'A': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'], 64 | 'B': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'], 65 | 'D': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'], 66 | 'E': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 67 | 512, 512, 512, 512, 'M'], 68 | } 69 | 70 | 71 | def vgg11(): 72 | """VGG 11-layer model (configuration "A")""" 73 | return VGG(make_layers(cfg['A'])) 74 | 75 | 76 | def vgg11_bn(): 77 | """VGG 11-layer model (configuration "A") with batch normalization""" 78 | return VGG(make_layers(cfg['A'], batch_norm=True)) 79 | 80 | 81 | def vgg13(): 82 | """VGG 13-layer model (configuration "B")""" 83 | return VGG(make_layers(cfg['B'])) 84 | 85 | 86 | def vgg13_bn(): 87 | """VGG 13-layer model (configuration "B") with batch normalization""" 88 | return VGG(make_layers(cfg['B'], batch_norm=True)) 89 | 90 | 91 | def vgg16(): 92 | """VGG 16-layer model (configuration "D")""" 93 | return VGG(make_layers(cfg['D'])) 94 | 95 | 96 | def vgg16_bn(): 97 | """VGG 16-layer model (configuration "D") with batch normalization""" 98 | return VGG(make_layers(cfg['D'], batch_norm=True)) 99 | 100 | 101 | def vgg19(): 102 | """VGG 19-layer model (configuration "E")""" 103 | return VGG(make_layers(cfg['E'])) 104 | 105 | 106 | def vgg19_bn(): 107 | """VGG 19-layer model (configuration 'E') with batch normalization""" 108 | return VGG(make_layers(cfg['E'], batch_norm=True)) -------------------------------------------------------------------------------- /blitz/modules/tests/embadding_bayesian_test.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import torch 3 | from torch import nn 4 | 5 | from blitz.modules import BayesianEmbedding 6 | from blitz.modules.base_bayesian_module import BayesianModule 7 | 8 | class TestLinearBayesian(unittest.TestCase): 9 | 10 | def test_init_bayesian_layer(self): 11 | module = BayesianEmbedding(10, 10) 12 | pass 13 | 14 | def test_infer_shape_1_sample(self): 15 | blinear = BayesianEmbedding(10, 10) 16 | linear = nn.Embedding(10, 10) 17 | 18 | to_feed = torch.Tensor([i for i in range(9)]).unsqueeze(0).long() 19 | 20 | b_infer = linear(to_feed) 21 | l_infer = blinear(to_feed) 22 | 23 | self.assertEqual(b_infer.shape, l_infer.shape) 24 | self.assertEqual((b_infer == b_infer).all(), torch.tensor(True)) 25 | pass 26 | 27 | def test_variational_inference(self): 28 | #create module, check if inference is variating 29 | blinear = BayesianEmbedding(10, 10) 30 | linear = nn.Embedding(10, 10) 31 | 32 | to_feed = torch.Tensor([i for i in range(9)]).unsqueeze(0).long() 33 | 34 | self.assertEqual((blinear(to_feed) != blinear(to_feed)).any(), torch.tensor(True)) 35 | self.assertEqual((linear(to_feed) == linear(to_feed)).all(), torch.tensor(True)) 36 | pass 37 | 38 | def test_freeze_module(self): 39 | #create module, freeze 40 | #check if two inferences keep equal 41 | blinear = BayesianEmbedding(10, 10) 42 | to_feed = torch.Tensor([i for i in range(9)]).unsqueeze(0).long() 43 | 44 | self.assertEqual((blinear(to_feed) != blinear(to_feed)).any(), torch.tensor(True)) 45 | 46 | frozen_feedforward = blinear.forward_frozen(to_feed) 47 | blinear.freeze = True 48 | self.assertEqual((blinear.forward(to_feed) == frozen_feedforward).all(), torch.tensor(True)) 49 | 50 | def test_kl_divergence(self): 51 | #create model, sample weights 52 | #check if kl divergence between apriori and a posteriori is working 53 | blinear = BayesianEmbedding(10, 10) 54 | to_feed = torch.Tensor([i for i in range(9)]).unsqueeze(0).long() 55 | 56 | predicted = blinear(to_feed) 57 | complexity_cost = blinear.log_variational_posterior - blinear.log_prior 58 | 59 | self.assertEqual((complexity_cost == complexity_cost).all(), torch.tensor(True)) 60 | pass 61 | 62 | def test_inheritance(self): 63 | 64 | #check if bayesian linear has nn.Module and BayesianModule classes 65 | blinear = BayesianEmbedding(10, 10) 66 | self.assertEqual(isinstance(blinear, (nn.Module)), True) 67 | self.assertEqual(isinstance(blinear, (BayesianModule)), True) 68 | 69 | def test_sequential_cpu(self): 70 | #check if we can create sequential models chaning our Bayesian Linear layers 71 | model = nn.Sequential(BayesianEmbedding(10, 10), 72 | nn.LSTM(10, 15),) 73 | 74 | to_feed = torch.Tensor([i for i in range(9)]).unsqueeze(0).long() 75 | #if this works, the test will pass 76 | result = model(to_feed) 77 | pass 78 | 79 | def test_sequential_cuda(self): 80 | #check if we can create sequential models chaning our Bayesian Linear layers 81 | device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') 82 | 83 | model = nn.Sequential(BayesianEmbedding(10, 10), 84 | nn.LSTM(10, 15),).to(device) 85 | 86 | to_feed = torch.Tensor([i for i in range(9)]).unsqueeze(0).long().to(device) 87 | #if this works, the test will pass 88 | result = model(to_feed) 89 | pass 90 | 91 | if __name__ == "__main__": 92 | unittest.main() -------------------------------------------------------------------------------- /blitz/modules/tests/linear_bayesian_layer_test.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import torch 3 | from torch import nn 4 | 5 | from blitz.modules import BayesianLinear 6 | from blitz.modules.base_bayesian_module import BayesianModule 7 | 8 | class TestLinearBayesian(unittest.TestCase): 9 | 10 | def test_init_bayesian_layer(self): 11 | module = BayesianLinear(10, 10) 12 | pass 13 | 14 | def test_infer_shape_1_sample(self): 15 | blinear = BayesianLinear(10, 10) 16 | linear = nn.Linear(10, 10) 17 | to_feed = torch.ones((1, 10)) 18 | 19 | b_infer = linear(to_feed) 20 | l_infer = blinear(to_feed) 21 | 22 | self.assertEqual(b_infer.shape, l_infer.shape) 23 | self.assertEqual((b_infer == b_infer).all(), torch.tensor(True)) 24 | pass 25 | 26 | def test_variational_inference(self): 27 | #create module, check if inference is variating 28 | blinear = BayesianLinear(10, 10) 29 | linear = nn.Linear(10, 10) 30 | 31 | to_feed = torch.ones((1, 10)) 32 | self.assertEqual((blinear(to_feed) != blinear(to_feed)).any(), torch.tensor(True)) 33 | self.assertEqual((linear(to_feed) == linear(to_feed)).all(), torch.tensor(True)) 34 | pass 35 | 36 | def test_freeze_module(self): 37 | #create module, freeze 38 | #check if two inferences keep equal 39 | blinear = BayesianLinear(10, 10) 40 | to_feed = torch.ones((1, 10)) 41 | self.assertEqual((blinear(to_feed) != blinear(to_feed)).any(), torch.tensor(True)) 42 | 43 | frozen_feedforward = blinear.forward_frozen(to_feed) 44 | blinear.freeze = True 45 | self.assertEqual((blinear.forward(to_feed) == frozen_feedforward).all(), torch.tensor(True)) 46 | 47 | def test_no_bias(self): 48 | blinear = BayesianLinear(10, 10, bias=False) 49 | to_feed = torch.ones((1, 10)) 50 | self.assertEqual((blinear(to_feed) != blinear(to_feed)).any(), torch.tensor(True)) 51 | pass 52 | 53 | def test_kl_divergence(self): 54 | #create model, sample weights 55 | #check if kl divergence between apriori and a posteriori is working 56 | blinear = BayesianLinear(10, 10) 57 | to_feed = torch.ones((1, 10)) 58 | 59 | predicted = blinear(to_feed) 60 | complexity_cost = blinear.log_variational_posterior - blinear.log_prior 61 | 62 | self.assertEqual((complexity_cost == complexity_cost).all(), torch.tensor(True)) 63 | pass 64 | 65 | def test_inheritance(self): 66 | 67 | #check if bayesian linear has nn.Module and BayesianModule classes 68 | blinear = BayesianLinear(10, 10) 69 | self.assertEqual(isinstance(blinear, (nn.Module)), True) 70 | self.assertEqual(isinstance(blinear, (BayesianModule)), True) 71 | 72 | def test_sequential_cpu(self): 73 | #check if we can create sequential models chaning our Bayesian Linear layers 74 | model = nn.Sequential(BayesianLinear(10, 10), 75 | nn.Linear(10, 15), 76 | BayesianLinear(15,10)) 77 | 78 | to_feed = torch.ones((1, 10)) 79 | #if this works, the test will pass 80 | result = model(to_feed) 81 | pass 82 | 83 | def test_sequential_cuda(self): 84 | #check if we can create sequential models chaning our Bayesian Linear layers 85 | device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') 86 | 87 | model = nn.Sequential(BayesianLinear(10, 10), 88 | nn.Linear(10, 15), 89 | BayesianLinear(15,10)).to(device) 90 | 91 | to_feed = torch.ones((1, 10)).to(device) 92 | #if this works, the test will pass 93 | result = model(to_feed) 94 | pass 95 | 96 | if __name__ == "__main__": 97 | unittest.main() -------------------------------------------------------------------------------- /blitz/examples/bayesian_regression_boston.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | import torch.optim as optim 5 | import numpy as np 6 | 7 | from blitz.modules import BayesianLinear 8 | from blitz.utils import variational_estimator 9 | 10 | from sklearn.datasets import load_boston 11 | from sklearn.preprocessing import StandardScaler 12 | from sklearn.model_selection import train_test_split 13 | 14 | X, y = load_boston(return_X_y=True) 15 | X = StandardScaler().fit_transform(X) 16 | y = StandardScaler().fit_transform(np.expand_dims(y, -1)) 17 | 18 | X_train, X_test, y_train, y_test = train_test_split(X, 19 | y, 20 | test_size=.25, 21 | random_state=42) 22 | 23 | 24 | X_train, y_train = torch.tensor(X_train).float(), torch.tensor(y_train).float() 25 | X_test, y_test = torch.tensor(X_test).float(), torch.tensor(y_test).float() 26 | 27 | 28 | @variational_estimator 29 | class BayesianRegressor(nn.Module): 30 | def __init__(self, input_dim, output_dim): 31 | super().__init__() 32 | #self.linear = nn.Linear(input_dim, output_dim) 33 | self.blinear1 = BayesianLinear(input_dim, 512) 34 | self.blinear2 = BayesianLinear(512, output_dim) 35 | 36 | def forward(self, x): 37 | x_ = self.blinear1(x) 38 | x_ = F.relu(x_) 39 | return self.blinear2(x_) 40 | 41 | 42 | def evaluate_regression(regressor, 43 | X, 44 | y, 45 | samples = 100, 46 | std_multiplier = 2): 47 | preds = [regressor(X) for i in range(samples)] 48 | preds = torch.stack(preds) 49 | means = preds.mean(axis=0) 50 | stds = preds.std(axis=0) 51 | ci_upper = means + (std_multiplier * stds) 52 | ci_lower = means - (std_multiplier * stds) 53 | ic_acc = (ci_lower <= y) * (ci_upper >= y) 54 | ic_acc = ic_acc.float().mean() 55 | return ic_acc, (ci_upper >= y).float().mean(), (ci_lower <= y).float().mean() 56 | 57 | device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') 58 | regressor = BayesianRegressor(13, 1).to(device) 59 | optimizer = optim.Adam(regressor.parameters(), lr=0.01) 60 | criterion = torch.nn.MSELoss() 61 | 62 | ds_train = torch.utils.data.TensorDataset(X_train, y_train) 63 | dataloader_train = torch.utils.data.DataLoader(ds_train, batch_size=16, shuffle=True) 64 | 65 | ds_test = torch.utils.data.TensorDataset(X_test, y_test) 66 | dataloader_test = torch.utils.data.DataLoader(ds_test, batch_size=16, shuffle=True) 67 | 68 | 69 | iteration = 0 70 | for epoch in range(1000): 71 | for i, (datapoints, labels) in enumerate(dataloader_train): 72 | optimizer.zero_grad() 73 | 74 | loss = regressor.sample_elbo(inputs=datapoints.to(device), 75 | labels=labels.to(device), 76 | criterion=criterion, 77 | sample_nbr=3, 78 | complexity_cost_weight=1/X_train.shape[0]) 79 | loss.backward() 80 | optimizer.step() 81 | 82 | iteration += 1 83 | if iteration%100==0: 84 | ic_acc, under_ci_upper, over_ci_lower = evaluate_regression(regressor, 85 | X_test.to(device), 86 | y_test.to(device), 87 | samples=25, 88 | std_multiplier=3) 89 | 90 | print("CI acc: {:.2f}, CI upper acc: {:.2f}, CI lower acc: {:.2f}".format(ic_acc, under_ci_upper, over_ci_lower)) 91 | print("Loss: {:.4f}".format(loss)) 92 | -------------------------------------------------------------------------------- /blitz/utils/layer_wrappers.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import types 3 | 4 | from blitz.modules.weight_sampler import TrainableRandomDistribution 5 | from blitz.losses import kl_divergence_from_nn 6 | from blitz.modules.base_bayesian_module import BayesianModule 7 | from blitz.modules import BayesianLSTM 8 | 9 | 10 | def copy_func(f, name=None): 11 | ''' 12 | return a function with same code, globals, defaults, closure, and 13 | name (or provide a new name) 14 | ''' 15 | fn = types.FunctionType(f.__code__, f.__globals__, name or f.__name__, 16 | f.__defaults__, f.__closure__) 17 | # in case f was given attrs (note this dict is a shallow copy): 18 | fn.__dict__.update(f.__dict__) 19 | return fn 20 | 21 | 22 | def Flipout(nn_module): 23 | """ 24 | Wrapper tha introduces flipout on the feedforwad operation of a BayesianModule layer in an non-intrusive way as in 25 | @misc{wen2018flipout, 26 | title={Flipout: Efficient Pseudo-Independent Weight Perturbations on Mini-Batches}, 27 | author={Yeming Wen and Paul Vicol and Jimmy Ba and Dustin Tran and Roger Grosse}, 28 | year={2018}, 29 | eprint={1803.04386}, 30 | archivePrefix={arXiv}, 31 | primaryClass={cs.LG} 32 | } 33 | Parameters: 34 | nn_module: torch.nn.Module, BayesianModule -> Torch neural network module 35 | """ 36 | 37 | class Flipout(nn_module): 38 | def __init__(self, *args, **kwargs): 39 | super().__init__(*args, **kwargs) 40 | 41 | if nn_module not in [BayesianLSTM, ]: 42 | def forward(self, x): 43 | outputs = super().forward_frozen(x) 44 | # getting the sign matrixes 45 | sign_input = x.clone().uniform_(-1, 1).sign() 46 | sign_output = outputs.clone().uniform_(-1, 1).sign() 47 | 48 | perturbed_outputs = super().forward(x * sign_input) * sign_output 49 | 50 | return outputs + perturbed_outputs 51 | else: 52 | def forward(self, x, states=None): 53 | outputs, states = super().forward_frozen(x, states) 54 | 55 | # getting the sign matrixes 56 | sign_input = x.clone().uniform_(-1, 1).sign() 57 | sign_output = outputs.clone().uniform_(-1, 1).sign() 58 | 59 | perturbed_outputs, perturbed_states = super().forward((x * sign_input), states) # * sign_output 60 | 61 | if not (type(states) == tuple): 62 | return (perturbed_outputs + outputs, states + perturbed_states) 63 | 64 | return (perturbed_outputs + outputs, (states[i] + perturbed_states[i] for i in range(len(states)))) 65 | 66 | return Flipout 67 | 68 | 69 | def Radial(nn_module): 70 | """ 71 | Wrapper tha introduces the Radial feature on the feedforwad operation of a BayesianModule layer in an non-intrusive way as in 72 | @misc{farquhar2019radial, 73 | title={Radial Bayesian Neural Networks: Beyond Discrete Support In Large-Scale Bayesian Deep Learning}, 74 | author={Sebastian Farquhar and Michael Osborne and Yarin Gal}, 75 | year={2019}, 76 | eprint={1907.00865}, 77 | archivePrefix={arXiv}, 78 | primaryClass={stat.ML} 79 | } 80 | Parameters: 81 | nn_module: torch.nn.Module, BayesianModule -> Torch neural network module 82 | """ 83 | 84 | def sample_radial(self): 85 | """ 86 | Samples weights by sampling form a Normal distribution, multiplying by a sigma, which is 87 | a function from a trainable parameter, and adding a mean sets those weights as the current ones 88 | We divide the random parameter per its norm to perform radial bnn inference 89 | returns: 90 | torch.tensor with same shape as self.mu and self.rho 91 | """ 92 | 93 | self.eps_w.data.normal_() 94 | self.sigma = torch.log1p(torch.exp(self.rho)) 95 | self.w = self.mu + self.sigma * (self.eps_weight / torch.norm(self.eps_weight)) 96 | return self.w 97 | 98 | setattr(nn_module, "sample", sample_radial) 99 | return nn_module -------------------------------------------------------------------------------- /blitz/modules/linear_bayesian_layer.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch import nn 3 | from torch.nn import functional as F 4 | from blitz.modules.base_bayesian_module import BayesianModule 5 | from blitz.modules.weight_sampler import TrainableRandomDistribution, PriorWeightDistribution 6 | 7 | 8 | class BayesianLinear(BayesianModule): 9 | """ 10 | Bayesian Linear layer, implements the linear layer proposed on Weight Uncertainity on Neural Networks 11 | (Bayes by Backprop paper). 12 | 13 | Its objective is be interactable with torch nn.Module API, being able even to be chained in nn.Sequential models with other non-this-lib layers 14 | 15 | parameters: 16 | in_fetaures: int -> incoming features for the layer 17 | out_features: int -> output features for the layer 18 | bias: bool -> whether the bias will exist (True) or set to zero (False) 19 | prior_sigma_1: float -> prior sigma on the mixture prior distribution 1 20 | prior_sigma_2: float -> prior sigma on the mixture prior distribution 2 21 | prior_pi: float -> pi on the scaled mixture prior 22 | posterior_mu_init float -> posterior mean for the weight mu init 23 | posterior_rho_init float -> posterior mean for the weight rho init 24 | freeze: bool -> wheter the model will start with frozen(deterministic) weights, or not 25 | 26 | """ 27 | def __init__(self, 28 | in_features, 29 | out_features, 30 | bias=True, 31 | prior_sigma_1 = 0.1, 32 | prior_sigma_2 = 0.4, 33 | prior_pi = 1, 34 | posterior_mu_init = 0, 35 | posterior_rho_init = -7.0, 36 | freeze = False, 37 | prior_dist = None): 38 | super().__init__() 39 | 40 | #our main parameters 41 | self.in_features = in_features 42 | self.out_features = out_features 43 | self.bias = bias 44 | self.freeze = freeze 45 | 46 | 47 | self.posterior_mu_init = posterior_mu_init 48 | self.posterior_rho_init = posterior_rho_init 49 | 50 | #parameters for the scale mixture prior 51 | self.prior_sigma_1 = prior_sigma_1 52 | self.prior_sigma_2 = prior_sigma_2 53 | self.prior_pi = prior_pi 54 | self.prior_dist = prior_dist 55 | 56 | # Variational weight parameters and sample 57 | self.weight_mu = nn.Parameter(torch.Tensor(out_features, in_features).normal_(posterior_mu_init, 0.1)) 58 | self.weight_rho = nn.Parameter(torch.Tensor(out_features, in_features).normal_(posterior_rho_init, 0.1)) 59 | self.weight_sampler = TrainableRandomDistribution(self.weight_mu, self.weight_rho) 60 | 61 | # Variational bias parameters and sample 62 | self.bias_mu = nn.Parameter(torch.Tensor(out_features).normal_(posterior_mu_init, 0.1)) 63 | self.bias_rho = nn.Parameter(torch.Tensor(out_features).normal_(posterior_rho_init, 0.1)) 64 | self.bias_sampler = TrainableRandomDistribution(self.bias_mu, self.bias_rho) 65 | 66 | # Priors (as BBP paper) 67 | self.weight_prior_dist = PriorWeightDistribution(self.prior_pi, self.prior_sigma_1, self.prior_sigma_2, dist = self.prior_dist) 68 | self.bias_prior_dist = PriorWeightDistribution(self.prior_pi, self.prior_sigma_1, self.prior_sigma_2, dist = self.prior_dist) 69 | self.log_prior = 0 70 | self.log_variational_posterior = 0 71 | 72 | def forward(self, x): 73 | # Sample the weights and forward it 74 | 75 | #if the model is frozen, return frozen 76 | if self.freeze: 77 | return self.forward_frozen(x) 78 | 79 | w = self.weight_sampler.sample() 80 | 81 | if self.bias: 82 | b = self.bias_sampler.sample() 83 | b_log_posterior = self.bias_sampler.log_posterior() 84 | b_log_prior = self.bias_prior_dist.log_prior(b) 85 | 86 | else: 87 | b = torch.zeros((self.out_features), device=x.device) 88 | b_log_posterior = 0 89 | b_log_prior = 0 90 | 91 | # Get the complexity cost 92 | self.log_variational_posterior = self.weight_sampler.log_posterior() + b_log_posterior 93 | self.log_prior = self.weight_prior_dist.log_prior(w) + b_log_prior 94 | 95 | return F.linear(x, w, b) 96 | 97 | def forward_frozen(self, x): 98 | """ 99 | Computes the feedforward operation with the expected value for weight and biases 100 | """ 101 | if self.bias: 102 | return F.linear(x, self.weight_mu, self.bias_mu) 103 | else: 104 | return F.linear(x, self.weight_mu, torch.zeros(self.out_features)) 105 | -------------------------------------------------------------------------------- /blitz/modules/base_bayesian_module.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch import nn 3 | import math 4 | 5 | class BayesianModule(nn.Module): 6 | """ 7 | creates base class for BNN, in order to enable specific behavior 8 | """ 9 | def init(self): 10 | super().__init__() 11 | 12 | 13 | class BayesianRNN(BayesianModule): 14 | """ 15 | implements base class for B-RNN to enable posterior sharpening 16 | """ 17 | def __init__(self, 18 | sharpen=False): 19 | super().__init__() 20 | 21 | self.weight_ih_mu = None 22 | self.weight_hh_mu = None 23 | self.bias = None 24 | 25 | self.weight_ih_sampler = None 26 | self.weight_hh_sampler = None 27 | self.bias_sampler = None 28 | 29 | self.weight_ih = None 30 | self.weight_hh = None 31 | self.bias = None 32 | 33 | self.sharpen = sharpen 34 | 35 | self.weight_ih_eta = None 36 | self.weight_hh_eta = None 37 | self.bias_eta = None 38 | self.ff_parameters = None 39 | self.loss_to_sharpen = None 40 | 41 | 42 | def sample_weights(self): 43 | pass 44 | 45 | def init_sharpen_parameters(self): 46 | if self.sharpen: 47 | self.weight_ih_eta = nn.Parameter(torch.Tensor(self.weight_ih_mu.size())) 48 | self.weight_hh_eta = nn.Parameter(torch.Tensor(self.weight_hh_mu.size())) 49 | self.bias_eta = nn.Parameter(torch.Tensor(self.bias_mu.size())) 50 | 51 | self.ff_parameters = [] 52 | 53 | self.init_eta() 54 | 55 | def init_eta(self): 56 | stdv = 1.0 / math.sqrt(self.weight_hh_eta.shape[0]) #correspond to hidden_units parameter 57 | self.weight_ih_eta.data.uniform_(-stdv, stdv) 58 | self.weight_hh_eta.data.uniform_(-stdv, stdv) 59 | self.bias_eta.data.uniform_(-stdv, stdv) 60 | 61 | def set_loss_to_sharpen(self, loss): 62 | self.loss_to_sharpen = loss 63 | 64 | def sharpen_posterior(self, loss, input_shape): 65 | """ 66 | sharpens the posterior distribution by using the algorithm proposed in 67 | @article{DBLP:journals/corr/FortunatoBV17, 68 | author = {Meire Fortunato and 69 | Charles Blundell and 70 | Oriol Vinyals}, 71 | title = {Bayesian Recurrent Neural Networks}, 72 | journal = {CoRR}, 73 | volume = {abs/1704.02798}, 74 | year = {2017}, 75 | url = {http://arxiv.org/abs/1704.02798}, 76 | archivePrefix = {arXiv}, 77 | eprint = {1704.02798}, 78 | timestamp = {Mon, 13 Aug 2018 16:48:21 +0200}, 79 | biburl = {https://dblp.org/rec/journals/corr/FortunatoBV17.bib}, 80 | bibsource = {dblp computer science bibliography, https://dblp.org} 81 | } 82 | """ 83 | bs, seq_len, in_size = input_shape 84 | gradients = torch.autograd.grad(outputs=loss, 85 | inputs=self.ff_parameters, 86 | grad_outputs=torch.ones(loss.size()).to(loss.device), 87 | create_graph=True, 88 | retain_graph=True, 89 | only_inputs=True) 90 | 91 | grad_weight_ih, grad_weight_hh, grad_bias = gradients 92 | 93 | #to generate sigmas on the weight sampler 94 | _ = self.sample_weights() 95 | 96 | weight_ih_sharpened = self.weight_ih_mu - self.weight_ih_eta * grad_weight_ih + self.weight_ih_sampler.sigma 97 | weight_hh_sharpened = self.weight_hh_mu - self.weight_hh_eta * grad_weight_hh + self.weight_hh_sampler.sigma 98 | bias_sharpened = self.bias_mu - self.bias_eta * grad_bias + self.bias_sampler.sigma 99 | 100 | if self.bias is not None: 101 | b_log_posterior = self.bias_sampler.log_posterior(w=bias_sharpened) 102 | b_log_prior_ = self.bias_prior_dist.log_prior(bias_sharpened) 103 | 104 | else: 105 | b_log_posterior = b_log_prior = 0 106 | 107 | 108 | self.log_variational_posterior += (self.weight_ih_sampler.log_posterior(w=weight_ih_sharpened) + b_log_posterior + self.weight_hh_sampler.log_posterior(w=weight_hh_sharpened)) / seq_len 109 | 110 | self.log_prior += self.weight_ih_prior_dist.log_prior(weight_ih_sharpened) + b_log_prior + self.weight_hh_prior_dist.log_prior(weight_hh_sharpened) / seq_len 111 | 112 | return weight_ih_sharpened, weight_hh_sharpened, bias_sharpened 113 | 114 | -------------------------------------------------------------------------------- /blitz/modules/embedding_bayesian_layer.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch import nn 3 | from torch.nn import functional as F 4 | from blitz.modules.base_bayesian_module import BayesianModule 5 | from blitz.modules.weight_sampler import TrainableRandomDistribution, PriorWeightDistribution 6 | 7 | class BayesianEmbedding(BayesianModule): 8 | """ 9 | Bayesian Embedding layer, implements the embedding layer proposed on Weight Uncertainity on Neural Networks 10 | (Bayes by Backprop paper). 11 | 12 | Its objective is be interactable with torch nn.Module API, being able even to be chained in nn.Sequential models with other non-this-lib layers 13 | 14 | parameters: 15 | num_embedding int -> Size of the vocabulary 16 | embedding_dim int -> Dimension of the embedding 17 | prior_sigma_1 float -> sigma of one of the prior w distributions to mixture 18 | prior_sigma_2 float -> sigma of one of the prior w distributions to mixture 19 | prior_pi float -> factor to scale the gaussian mixture of the model prior distribution 20 | freeze -> wheter the model is instaced as frozen (will use deterministic weights on the feedforward op) 21 | padding_idx int -> If given, pads the output with the embedding vector at padding_idx (initialized to zeros) whenever it encounters the index 22 | max_norm float -> If given, each embedding vector with norm larger than max_norm is renormalized to have norm max_norm. 23 | norm_type float -> The p of the p-norm to compute for the max_norm option. Default 2. 24 | scale_grad_by_freq -> If given, this will scale gradients by the inverse of frequency of the words in the mini-batch. Default False. 25 | sparse bool -> If True, gradient w.r.t. weight matrix will be a sparse tensor. See Notes for more details regarding sparse gradients. 26 | posterior_mu_init float -> posterior mean for the weight mu init 27 | posterior_rho_init float -> posterior mean for the weight rho init 28 | 29 | 30 | """ 31 | def __init__(self, 32 | num_embeddings, 33 | embedding_dim, 34 | padding_idx=None, 35 | max_norm=None, 36 | norm_type=2., 37 | scale_grad_by_freq=False, 38 | sparse=False, 39 | prior_sigma_1 = 0.1, 40 | prior_sigma_2 = 0.002, 41 | prior_pi = 1, 42 | posterior_mu_init = 0, 43 | posterior_rho_init = -6.0, 44 | freeze = False, 45 | prior_dist = None): 46 | super().__init__() 47 | 48 | self.freeze = freeze 49 | 50 | #parameters for the scale mixture prior 51 | self.prior_sigma_1 = prior_sigma_1 52 | self.prior_sigma_2 = prior_sigma_2 53 | self.posterior_mu_init = posterior_mu_init 54 | self.posterior_rho_init = posterior_rho_init 55 | 56 | self.prior_pi = prior_pi 57 | self.prior_dist = prior_dist 58 | 59 | self.num_embeddings = num_embeddings 60 | self.embedding_dim = embedding_dim 61 | self.padding_idx = padding_idx 62 | self.max_norm = max_norm 63 | self.norm_type = norm_type 64 | self.scale_grad_by_freq = scale_grad_by_freq 65 | self.sparse = sparse 66 | 67 | # Variational weight parameters and sample 68 | self.weight_mu = nn.Parameter(torch.Tensor(num_embeddings, embedding_dim).normal_(posterior_mu_init, 0.1)) 69 | self.weight_rho = nn.Parameter(torch.Tensor(num_embeddings, embedding_dim).normal_(posterior_rho_init, 0.1)) 70 | self.weight_sampler = TrainableRandomDistribution(self.weight_mu, self.weight_rho) 71 | 72 | # Priors (as BBP paper) 73 | self.weight_prior_dist = PriorWeightDistribution(self.prior_pi, self.prior_sigma_1, self.prior_sigma_2, dist = self.prior_dist) 74 | self.log_prior = 0 75 | self.log_variational_posterior = 0 76 | 77 | def forward(self, x): 78 | # Sample the weights and forward it 79 | 80 | #if the model is frozen, return frozen 81 | if self.freeze: 82 | return self.forward_frozen(x) 83 | 84 | w = self.weight_sampler.sample() 85 | 86 | # Get the complexity cost 87 | self.log_variational_posterior = self.weight_sampler.log_posterior() 88 | self.log_prior = self.weight_prior_dist.log_prior(w) 89 | 90 | return F.embedding(x, 91 | w, 92 | self.padding_idx, 93 | self.max_norm, 94 | self.norm_type, 95 | self.scale_grad_by_freq, 96 | self.sparse) 97 | 98 | def forward_frozen(self, x): 99 | return F.embedding(x, 100 | self.weight_mu, 101 | self.padding_idx, 102 | self.max_norm, 103 | self.norm_type, 104 | self.scale_grad_by_freq, 105 | self.sparse) -------------------------------------------------------------------------------- /blitz/utils/variational_estimator.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import numpy as np 3 | 4 | from blitz.modules.weight_sampler import TrainableRandomDistribution 5 | from blitz.losses import kl_divergence_from_nn 6 | from blitz.modules.base_bayesian_module import BayesianModule, BayesianRNN 7 | 8 | def variational_estimator(nn_class): 9 | """ 10 | This decorator adds some util methods to a nn.Module, in order to facilitate the handling of Bayesian Deep Learning features 11 | 12 | Parameters: 13 | nn_class: torch.nn.Module -> Torch neural network module 14 | 15 | Returns a nn.Module with methods for: 16 | (1) Gathering the KL Divergence along its BayesianModules; 17 | (2) Sample the Elbo Loss along its variational inferences (helps training) 18 | (3) Freeze the model, in order to predict using only their weight distribution means 19 | (4) Specifying the variational parameters by using some prior weights after training the NN as a deterministic model 20 | """ 21 | 22 | def nn_kl_divergence(self): 23 | """Returns the sum of the KL divergence of each of the BayesianModules of the model, which are from 24 | their posterior current distribution of weights relative to a scale-mixtured prior (and simpler) distribution of weights 25 | 26 | Parameters: 27 | N/a 28 | 29 | Returns torch.tensor with 0 dim. 30 | 31 | """ 32 | return kl_divergence_from_nn(self) 33 | 34 | setattr(nn_class, "nn_kl_divergence", nn_kl_divergence) 35 | 36 | def sample_elbo(self, 37 | inputs, 38 | labels, 39 | criterion, 40 | sample_nbr, 41 | complexity_cost_weight=1): 42 | 43 | """ Samples the ELBO Loss for a batch of data, consisting of inputs and corresponding-by-index labels 44 | The ELBO Loss consists of the sum of the KL Divergence of the model 45 | (explained above, interpreted as a "complexity part" of the loss) 46 | with the actual criterion - (loss function) of optimization of our model 47 | (the performance part of the loss). 48 | As we are using variational inference, it takes several (quantified by the parameter sample_nbr) Monte-Carlo 49 | samples of the weights in order to gather a better approximation for the loss. 50 | Parameters: 51 | inputs: torch.tensor -> the input data to the model 52 | labels: torch.tensor -> label data for the performance-part of the loss calculation 53 | The shape of the labels must match the label-parameter shape of the criterion (one hot encoded or as index, if needed) 54 | criterion: torch.nn.Module, custom criterion (loss) function, torch.nn.functional function -> criterion to gather 55 | the performance cost for the model 56 | sample_nbr: int -> The number of times of the weight-sampling and predictions done in our Monte-Carlo approach to 57 | gather the loss to be .backwarded in the optimization of the model. 58 | 59 | """ 60 | 61 | loss = 0 62 | for _ in range(sample_nbr): 63 | outputs = self(inputs) 64 | loss += criterion(outputs, labels) 65 | loss += self.nn_kl_divergence() * complexity_cost_weight 66 | return loss / sample_nbr 67 | 68 | setattr(nn_class, "sample_elbo", sample_elbo) 69 | 70 | def sample_elbo_detailed_loss(self, 71 | inputs, 72 | labels, 73 | criterion, 74 | sample_nbr, 75 | complexity_cost_weight=1): 76 | 77 | """ Samples the ELBO Loss for a batch of data, consisting of inputs and corresponding-by-index labels. 78 | This version of the function returns the performance part and complexity part of the loss individually 79 | as well as an array of predictions 80 | 81 | The ELBO Loss consists of the sum of the KL Divergence of the model 82 | (explained above, interpreted as a "complexity part" of the loss) 83 | with the actual criterion - (loss function) of optimization of our model 84 | (the performance part of the loss). 85 | 86 | As we are using variational inference, it takes several (quantified by the parameter sample_nbr) Monte-Carlo 87 | samples of the weights in order to gather a better approximation for the loss. 88 | 89 | Parameters: 90 | inputs: torch.tensor -> the input data to the model 91 | labels: torch.tensor -> label data for the performance-part of the loss calculation 92 | The shape of the labels must match the label-parameter shape of the criterion (one hot encoded or as index, if needed) 93 | criterion: torch.nn.Module, custom criterion (loss) function, torch.nn.functional function -> criterion to gather 94 | the performance cost for the model 95 | sample_nbr: int -> The number of times of the weight-sampling and predictions done in our Monte-Carlo approach to 96 | gather the loss to be .backwarded in the optimization of the model. 97 | Returns: 98 | array of predictions 99 | ELBO Loss 100 | performance part 101 | complexity part 102 | 103 | """ 104 | 105 | loss = 0 106 | likelihood_cost = 0 107 | complexity_cost = 0 108 | # Array to collect the outputs 109 | y_hat = [] 110 | for _ in range(sample_nbr): 111 | outputs = self(inputs) 112 | y_hat.append(outputs.cpu().detach().numpy()) 113 | likelihood_cost += criterion(outputs, labels) 114 | complexity_cost += self.nn_kl_divergence() * complexity_cost_weight 115 | return np.array(y_hat), (likelihood_cost + complexity_cost) / sample_nbr,\ 116 | likelihood_cost / sample_nbr,\ 117 | complexity_cost / sample_nbr 118 | 119 | setattr(nn_class, "sample_elbo_detailed_loss", sample_elbo_detailed_loss) 120 | 121 | def freeze_model(self): 122 | """ 123 | Freezes the model by making it predict using only the expected value to their BayesianModules' weights distributions 124 | """ 125 | for module in self.modules(): 126 | if isinstance(module, (BayesianModule)): 127 | module.freeze = True 128 | 129 | setattr(nn_class, "freeze_", freeze_model) 130 | 131 | def unfreeze_model(self): 132 | """ 133 | Unfreezes the model by letting it draw its weights with uncertanity from their correspondent distributions 134 | """ 135 | 136 | for module in self.modules(): 137 | if isinstance(module, (BayesianModule)): 138 | module.freeze = False 139 | 140 | setattr(nn_class, "unfreeze_", unfreeze_model) 141 | 142 | def moped(self, delta=0.1): 143 | """ 144 | Sets the sigma for the posterior distribution to delta * mu as proposed in 145 | 146 | @misc{krishnan2019specifying, 147 | title={Specifying Weight Priors in Bayesian Deep Neural Networks with Empirical Bayes}, 148 | author={Ranganath Krishnan and Mahesh Subedar and Omesh Tickoo}, 149 | year={2019}, 150 | eprint={1906.05323}, 151 | archivePrefix={arXiv}, 152 | primaryClass={cs.NE} 153 | } 154 | 155 | 156 | """ 157 | for module in self.modules(): 158 | if isinstance(module, (BayesianModule)): 159 | 160 | for attr in module.modules(): 161 | if isinstance(attr, (TrainableRandomDistribution)): 162 | attr.rho.data = torch.log(torch.expm1(delta * torch.abs(attr.mu.data) ) + 1e-10) 163 | self.unfreeze_() 164 | 165 | setattr(nn_class, 'MOPED_', moped) 166 | 167 | def mfvi_forward(self, inputs, sample_nbr=10): 168 | """ 169 | Performs mean-field variational inference for the variational estimator model: 170 | Performs sample_nbr forward passes with uncertainty on the weights, returning its mean and standard deviation 171 | 172 | Parameters: 173 | inputs: torch.tensor -> the input data to the model 174 | sample_nbr: int -> number of forward passes to be done on the data 175 | Returns: 176 | mean_: torch.tensor -> mean of the perdictions along each of the features of each datapoint on the batch axis 177 | std_: torch.tensor -> std of the predictions along each of the features of each datapoint on the batch axis 178 | 179 | 180 | """ 181 | result = torch.stack([self(inputs) for _ in range(sample_nbr)]) 182 | return result.mean(dim=0), result.std(dim=0) 183 | 184 | setattr(nn_class, 'mfvi_forward', mfvi_forward) 185 | 186 | def forward_with_sharpening(self, x, labels, criterion): 187 | preds = self(x) 188 | loss = criterion(preds, labels) 189 | 190 | for module in self.modules(): 191 | if isinstance(module, (BayesianRNN)): 192 | module.loss_to_sharpen = loss 193 | 194 | y_hat: self(x) 195 | 196 | for module in self.modules(): 197 | if isinstance(module, (BayesianRNN)): 198 | module.loss_to_sharpen = None 199 | 200 | return self(x,) 201 | 202 | setattr(nn_class, 'forward_with_sharpening', forward_with_sharpening) 203 | 204 | 205 | 206 | 207 | return nn_class 208 | -------------------------------------------------------------------------------- /blitz/utils/tests/variational_estimator_test.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import torch 3 | from torch import nn 4 | import torchvision.datasets as dsets 5 | import torchvision.transforms as transforms 6 | 7 | from blitz.modules import BayesianConv2d, BayesianLinear, BayesianLSTM, BayesianEmbedding, TrainableRandomDistribution, BayesianGRU 8 | from blitz.losses import kl_divergence_from_nn 9 | from blitz.utils import variational_estimator 10 | 11 | class TestVariationalInference(unittest.TestCase): 12 | 13 | def test_kl_divergence(self): 14 | #create model 15 | #do two inferences over same datapoint, check if different 16 | 17 | to_feed = torch.ones((1, 10)) 18 | 19 | @variational_estimator 20 | class VariationalEstimator(nn.Module): 21 | def __init__(self): 22 | super().__init__() 23 | self.blinear = BayesianLinear(10, 10) 24 | 25 | def forward(self, x): 26 | return self.blinear(x) 27 | 28 | model = VariationalEstimator() 29 | predicted = model(to_feed) 30 | 31 | complexity_cost = model.nn_kl_divergence() 32 | kl_complexity_cost = kl_divergence_from_nn(model) 33 | 34 | self.assertEqual((complexity_cost == kl_complexity_cost).all(), torch.tensor(True)) 35 | 36 | def test_elbo_sampler(self): 37 | dataset = dsets.MNIST(root="./data", 38 | train=True, 39 | transform=transforms.ToTensor(), 40 | download=True 41 | ) 42 | 43 | dataloader = torch.utils.data.DataLoader(dataset=dataset, 44 | batch_size=16, 45 | shuffle=True) 46 | 47 | batch = next(iter(dataloader)) 48 | 49 | @variational_estimator 50 | class BayesianMLP(nn.Module): 51 | def __init__(self, input_dim, output_dim): 52 | super().__init__() 53 | #self.linear = nn.Linear(input_dim, output_dim) 54 | self.blinear1 = BayesianLinear(input_dim, 512) 55 | self.blinear2 = BayesianLinear(512, output_dim) 56 | 57 | def forward(self, x): 58 | x_ = x.view(-1, 28 * 28) 59 | x_ = self.blinear1(x_) 60 | return self.blinear2(x_) 61 | 62 | net = BayesianMLP(28*28, 10) 63 | elbo = net.sample_elbo(inputs=batch[0], 64 | labels=batch[1], 65 | criterion=torch.nn.CrossEntropyLoss(), 66 | sample_nbr=5, 67 | complexity_cost_weight=1) 68 | 69 | 70 | elbo = net.sample_elbo(inputs=batch[0], 71 | labels=batch[1], 72 | criterion=torch.nn.CrossEntropyLoss(), 73 | sample_nbr=5, 74 | complexity_cost_weight=0) 75 | 76 | self.assertEqual((elbo==elbo).all(), torch.tensor(True)) 77 | 78 | pass 79 | 80 | def test_elbo_detailed_loss_sampler(self): 81 | dataset = dsets.MNIST(root="./data", 82 | train=True, 83 | transform=transforms.ToTensor(), 84 | download=True 85 | ) 86 | 87 | dataloader = torch.utils.data.DataLoader(dataset=dataset, 88 | batch_size=16, 89 | shuffle=True) 90 | 91 | batch = next(iter(dataloader)) 92 | 93 | @variational_estimator 94 | class BayesianMLP(nn.Module): 95 | def __init__(self, input_dim, output_dim): 96 | super().__init__() 97 | # self.linear = nn.Linear(input_dim, output_dim) 98 | self.blinear1 = BayesianLinear(input_dim, 512) 99 | self.blinear2 = BayesianLinear(512, output_dim) 100 | 101 | def forward(self, x): 102 | x_ = x.view(-1, 28 * 28) 103 | x_ = self.blinear1(x_) 104 | return self.blinear2(x_) 105 | 106 | net = BayesianMLP(28 * 28, 10) 107 | elbo = net.sample_elbo_detailed_loss(inputs=batch[0], 108 | labels=batch[1], 109 | criterion=torch.nn.CrossEntropyLoss(), 110 | sample_nbr=5, 111 | complexity_cost_weight=1) 112 | 113 | elbo = net.sample_elbo_detailed_loss(inputs=batch[0], 114 | labels=batch[1], 115 | criterion=torch.nn.CrossEntropyLoss(), 116 | sample_nbr=5, 117 | complexity_cost_weight=0) 118 | 119 | self.assertEqual((elbo == elbo), True) 120 | self.assertEqual(elbo[3], torch.tensor(0)) 121 | self.assertEqual(len(elbo), 4) # There are 4 return values 122 | self.assertEqual(len(elbo[0]), 5) # Matches the number of samples for Monte-Carlo-sampling 123 | self.assertEqual(len(elbo[0][0]), 16) # Matches the batch size 124 | self.assertEqual(len(elbo[0][0][0]), 10) # Matches the output size of the neural network 125 | 126 | pass 127 | 128 | def test_freeze_estimator(self): 129 | #create model, freeze it 130 | #infer two times on same datapoint, check if all equal 131 | dataset = dsets.MNIST(root="./data", 132 | train=True, 133 | transform=transforms.ToTensor(), 134 | download=True 135 | ) 136 | 137 | dataloader = torch.utils.data.DataLoader(dataset=dataset, 138 | batch_size=16, 139 | shuffle=True) 140 | 141 | batch = next(iter(dataloader)) 142 | 143 | @variational_estimator 144 | class BayesianMLP(nn.Module): 145 | def __init__(self, input_dim, output_dim): 146 | super().__init__() 147 | #self.linear = nn.Linear(input_dim, output_dim) 148 | self.blinear1 = BayesianLinear(input_dim, 512) 149 | self.blinear2 = BayesianLinear(512, output_dim) 150 | 151 | def forward(self, x): 152 | x_ = x.view(-1, 28 * 28) 153 | x_ = self.blinear1(x_) 154 | return self.blinear2(x_) 155 | 156 | net = BayesianMLP(28*28, 10) 157 | self.assertEqual((net(batch[0])!=net(batch[0])).any(), torch.tensor(True)) 158 | 159 | net.freeze_() 160 | self.assertEqual((net(batch[0])==net(batch[0])).all(), torch.tensor(True)) 161 | 162 | net.unfreeze_() 163 | self.assertEqual((net(batch[0])!=net(batch[0])).any(), torch.tensor(True)) 164 | pass 165 | 166 | def test_moped(self): 167 | 168 | @variational_estimator 169 | class BayesianMLP(nn.Module): 170 | def __init__(self): 171 | super().__init__() 172 | self.blinear1 = BayesianLinear(10, 512) 173 | self.bconv = BayesianConv2d(3, 3, kernel_size=(3, 3), padding=1, bias=True) 174 | self.blstm = BayesianLSTM(10, 2) 175 | def forward(self, x): 176 | return x 177 | model = BayesianMLP() 178 | model.MOPED_() 179 | 180 | def test_mfvi(self): 181 | 182 | @variational_estimator 183 | class BayesianMLP(nn.Module): 184 | def __init__(self): 185 | super().__init__() 186 | self.nn = nn.Sequential(BayesianLinear(10, 7), 187 | BayesianLinear(7, 5)) 188 | def forward(self, x): 189 | return self.nn(x) 190 | 191 | net = BayesianMLP() 192 | t = torch.ones(3, 10) 193 | out_ = net(t) 194 | 195 | mean_, std_ = net.mfvi_forward(t, sample_nbr=5) 196 | self.assertEqual(out_.shape, mean_.shape) 197 | self.assertEqual(out_.shape, std_.shape) 198 | 199 | self.assertEqual((out_!=mean_).any(), torch.tensor(True)) 200 | self.assertEqual((std_!=0).any(), torch.tensor(True)) 201 | 202 | #we also check if, for the frozen model, the std is 0 and the mean is equal to any output 203 | net.freeze_() 204 | out__ = net(t) 205 | 206 | mean__, std__ = net.mfvi_forward(t, sample_nbr=5) 207 | 208 | self.assertEqual(out__.shape, mean__.shape) 209 | self.assertEqual(out__.shape, std__.shape) 210 | 211 | self.assertEqual((std__==0).all(), torch.tensor(True)) 212 | 213 | def test_sharpen_forward(self): 214 | 215 | @variational_estimator 216 | class BayesianMLP(nn.Module): 217 | def __init__(self): 218 | super().__init__() 219 | self.lstm1 = BayesianLSTM(3, 5, sharpen=True) 220 | self.gru1 = BayesianGRU(5, 3, sharpen=True) 221 | 222 | def forward(self, x): 223 | a1, _ = self.lstm1(x) 224 | a2, _ = self.gru1(a1) 225 | return a2 226 | 227 | net = BayesianMLP() 228 | criterion = nn.MSELoss() 229 | in_tensor = torch.ones(4, 5, 3) 230 | label = in_tensor.clone().detach().normal_() 231 | 232 | y_hat = net.forward_with_sharpening(in_tensor, labels=label, criterion=criterion) 233 | 234 | criterion(y_hat, label).backward() 235 | pass 236 | 237 | 238 | if __name__ == "__main__": 239 | unittest.main() -------------------------------------------------------------------------------- /blitz/modules/gru_bayesian_layer.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch import nn 3 | from torch.nn import functional as F 4 | from blitz.modules.base_bayesian_module import BayesianModule, BayesianRNN 5 | from blitz.modules.weight_sampler import TrainableRandomDistribution, PriorWeightDistribution 6 | 7 | 8 | class BayesianGRU(BayesianRNN): 9 | """ 10 | Bayesian GRU layer, implements the linear layer proposed on Weight Uncertainity on Neural Networks 11 | (Bayes by Backprop paper). 12 | 13 | Its objective is be interactable with torch nn.Module API, being able even to be chained in nn.Sequential models with other non-this-lib layers 14 | 15 | parameters: 16 | in_fetaures: int -> incoming features for the layer 17 | out_features: int -> output features for the layer 18 | bias: bool -> whether the bias will exist (True) or set to zero (False) 19 | prior_sigma_1: float -> prior sigma on the mixture prior distribution 1 20 | prior_sigma_2: float -> prior sigma on the mixture prior distribution 2 21 | prior_pi: float -> pi on the scaled mixture prior 22 | posterior_mu_init float -> posterior mean for the weight mu init 23 | posterior_rho_init float -> posterior mean for the weight rho init 24 | freeze: bool -> wheter the model will start with frozen(deterministic) weights, or not 25 | 26 | """ 27 | def __init__(self, 28 | in_features, 29 | out_features, 30 | bias = True, 31 | prior_sigma_1 = 0.1, 32 | prior_sigma_2 = 0.002, 33 | prior_pi = 1, 34 | posterior_mu_init = 0, 35 | posterior_rho_init = -6.0, 36 | freeze = False, 37 | prior_dist = None, 38 | **kwargs): 39 | 40 | super().__init__(**kwargs) 41 | self.in_features = in_features 42 | self.out_features = out_features 43 | self.use_bias = bias 44 | self.freeze = freeze 45 | 46 | self.posterior_mu_init = posterior_mu_init 47 | self.posterior_rho_init = posterior_rho_init 48 | 49 | self.prior_sigma_1 = prior_sigma_1 50 | self.prior_sigma_2 = prior_sigma_2 51 | self.prior_pi = prior_pi 52 | self.prior_dist = prior_dist 53 | 54 | # Variational weight parameters and sample for weight ih 55 | self.weight_ih_mu = nn.Parameter(torch.Tensor(in_features, out_features * 4).normal_(posterior_mu_init, 0.1)) 56 | self.weight_ih_rho = nn.Parameter(torch.Tensor(in_features, out_features * 4).normal_(posterior_rho_init, 0.1)) 57 | self.weight_ih_sampler = TrainableRandomDistribution(self.weight_ih_mu, self.weight_ih_rho) 58 | self.weight_ih = None 59 | 60 | # Variational weight parameters and sample for weight hh 61 | self.weight_hh_mu = nn.Parameter(torch.Tensor(out_features, out_features * 4).normal_(posterior_mu_init, 0.1)) 62 | self.weight_hh_rho = nn.Parameter(torch.Tensor(out_features, out_features * 4).normal_(posterior_rho_init, 0.1)) 63 | self.weight_hh_sampler = TrainableRandomDistribution(self.weight_hh_mu, self.weight_hh_rho) 64 | self.weight_hh = None 65 | 66 | # Variational weight parameters and sample for bias 67 | self.bias_mu = nn.Parameter(torch.Tensor(out_features * 4).normal_(posterior_mu_init, 0.1)) 68 | self.bias_rho = nn.Parameter(torch.Tensor(out_features * 4).normal_(posterior_rho_init, 0.1)) 69 | self.bias_sampler = TrainableRandomDistribution(self.bias_mu, self.bias_rho) 70 | self.bias=None 71 | 72 | #our prior distributions 73 | self.weight_ih_prior_dist = PriorWeightDistribution(self.prior_pi, self.prior_sigma_1, self.prior_sigma_2, dist = self.prior_dist) 74 | self.weight_hh_prior_dist = PriorWeightDistribution(self.prior_pi, self.prior_sigma_1, self.prior_sigma_2, dist = self.prior_dist) 75 | self.bias_prior_dist = PriorWeightDistribution(self.prior_pi, self.prior_sigma_1, self.prior_sigma_2, dist = self.prior_dist) 76 | 77 | self.init_sharpen_parameters() 78 | 79 | self.log_prior = 0 80 | self.log_variational_posterior = 0 81 | 82 | def sample_weights(self): 83 | #sample weights 84 | weight_ih = self.weight_ih_sampler.sample() 85 | weight_hh = self.weight_hh_sampler.sample() 86 | 87 | #if use bias, we sample it, otherwise, we are using zeros 88 | if self.use_bias: 89 | b = self.bias_sampler.sample() 90 | b_log_posterior = self.bias_sampler.log_posterior() 91 | b_log_prior = self.bias_prior_dist.log_prior(b) 92 | 93 | else: 94 | b = 0 95 | b_log_posterior = 0 96 | b_log_prior = 0 97 | 98 | bias = b 99 | 100 | #gather weights variational posterior and prior likelihoods 101 | self.log_variational_posterior = self.weight_hh_sampler.log_posterior() + b_log_posterior + self.weight_ih_sampler.log_posterior() 102 | 103 | self.log_prior = self.weight_ih_prior_dist.log_prior(weight_ih) + b_log_prior + self.weight_hh_prior_dist.log_prior(weight_hh) 104 | 105 | self.ff_parameters = [weight_ih, weight_hh, bias] 106 | return weight_ih, weight_hh, bias 107 | 108 | def get_frozen_weights(self): 109 | 110 | #get all deterministic weights 111 | weight_ih = self.weight_ih_mu 112 | weight_hh = self.weight_hh_mu 113 | if self.use_bias: 114 | bias = self.bias_mu 115 | else: 116 | bias = 0 117 | 118 | return weight_ih, weight_hh, bias 119 | 120 | 121 | def forward_(self, 122 | x, 123 | hidden_states, 124 | sharpen_loss): 125 | 126 | if self.loss_to_sharpen is not None: 127 | sharpen_loss = self.loss_to_sharpen 128 | weight_ih, weight_hh, bias = self.sharpen_posterior(loss=sharpen_loss, input_shape=x.shape) 129 | elif (sharpen_loss is not None): 130 | sharpen_loss = sharpen_loss 131 | weight_ih, weight_hh, bias = self.sharpen_posterior(loss=sharpen_loss, input_shape=x.shape) 132 | 133 | else: 134 | weight_ih, weight_hh, bias = self.sample_weights() 135 | 136 | #Assumes x is of shape (batch, sequence, feature) 137 | bs, seq_sz, _ = x.size() 138 | hidden_seq = [] 139 | 140 | #if no hidden state, we are using zeros 141 | if hidden_states is None: 142 | h_t = torch.zeros(bs, self.out_features).to(x.device) 143 | else: 144 | h_t = hidden_states 145 | 146 | #simplifying our out features, and hidden seq list 147 | HS = self.out_features 148 | hidden_seq = [] 149 | 150 | for t in range(seq_sz): 151 | x_t = x[:, t, :] 152 | # batch the computations into a single matrix multiplication 153 | A_t = x_t @ weight_ih[:, :HS*2] + h_t @ weight_hh[:, :HS*2] + bias[:HS*2] 154 | 155 | r_t, z_t = ( 156 | torch.sigmoid(A_t[:, :HS]), 157 | torch.sigmoid(A_t[:, HS:HS*2]) 158 | ) 159 | 160 | n_t = torch.tanh(x_t @ weight_ih[:, HS*2:HS*3] + bias[HS*2:HS*3] + r_t * (h_t @ weight_hh[:, HS*3:HS*4] + bias[HS*3:HS*4])) 161 | h_t = (1 - z_t) * n_t + z_t * h_t 162 | 163 | hidden_seq.append(h_t.unsqueeze(0)) 164 | 165 | hidden_seq = torch.cat(hidden_seq, dim=0) 166 | # reshape from shape (sequence, batch, feature) to (batch, sequence, feature) 167 | hidden_seq = hidden_seq.transpose(0, 1).contiguous() 168 | 169 | return hidden_seq, h_t 170 | 171 | def forward_frozen(self, 172 | x, 173 | hidden_states): 174 | 175 | weight_ih, weight_hh, bias = self.get_frozen_weights() 176 | 177 | #Assumes x is of shape (batch, sequence, feature) 178 | bs, seq_sz, _ = x.size() 179 | hidden_seq = [] 180 | 181 | #if no hidden state, we are using zeros 182 | if hidden_states is None: 183 | h_t = torch.zeros(bs, self.out_features).to(x.device) 184 | else: 185 | h_t = hidden_states 186 | 187 | #simplifying our out features, and hidden seq list 188 | HS = self.out_features 189 | hidden_seq = [] 190 | 191 | for t in range(seq_sz): 192 | x_t = x[:, t, :] 193 | # batch the computations into a single matrix multiplication 194 | A_t = x_t @ weight_ih[:, :HS*2] + h_t @ weight_hh[:, :HS*2] + bias[:HS*2] 195 | 196 | r_t, z_t = ( 197 | torch.sigmoid(A_t[:, :HS]), 198 | torch.sigmoid(A_t[:, HS:HS*2]) 199 | ) 200 | 201 | n_t = torch.tanh(x_t @ weight_ih[:, HS*2:HS*3] + bias[HS*2:HS*3] + r_t * (h_t @ weight_hh[:, HS*3:HS*4] + bias[HS*3:HS*4])) 202 | h_t = (1 - z_t) * n_t + z_t * h_t 203 | 204 | hidden_seq.append(h_t.unsqueeze(0)) 205 | 206 | hidden_seq = torch.cat(hidden_seq, dim=0) 207 | # reshape from shape (sequence, batch, feature) to (batch, sequence, feature) 208 | hidden_seq = hidden_seq.transpose(0, 1).contiguous() 209 | 210 | return hidden_seq, h_t 211 | 212 | def forward(self, 213 | x, 214 | hidden_states=None, 215 | sharpen_loss=None): 216 | 217 | if self.freeze: 218 | return self.forward_frozen(x, hidden_states) 219 | 220 | if not self.sharpen: 221 | sharpen_loss = None 222 | 223 | return self.forward_(x, hidden_states, sharpen_loss) 224 | 225 | -------------------------------------------------------------------------------- /blitz/modules/lstm_bayesian_layer.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch import nn 3 | from torch.nn import functional as F 4 | from blitz.modules.base_bayesian_module import BayesianModule, BayesianRNN 5 | from blitz.modules.weight_sampler import TrainableRandomDistribution, PriorWeightDistribution 6 | 7 | 8 | class BayesianLSTM(BayesianRNN): 9 | """ 10 | Bayesian LSTM layer, implements the linear layer proposed on Weight Uncertainity on Neural Networks 11 | (Bayes by Backprop paper). 12 | 13 | Its objective is be interactable with torch nn.Module API, being able even to be chained in nn.Sequential models with other non-this-lib layers 14 | 15 | parameters: 16 | in_fetaures: int -> incoming features for the layer 17 | out_features: int -> output features for the layer 18 | bias: bool -> whether the bias will exist (True) or set to zero (False) 19 | prior_sigma_1: float -> prior sigma on the mixture prior distribution 1 20 | prior_sigma_2: float -> prior sigma on the mixture prior distribution 2 21 | prior_pi: float -> pi on the scaled mixture prior 22 | posterior_mu_init float -> posterior mean for the weight mu init 23 | posterior_rho_init float -> posterior mean for the weight rho init 24 | freeze: bool -> wheter the model will start with frozen(deterministic) weights, or not 25 | 26 | """ 27 | def __init__(self, 28 | in_features, 29 | out_features, 30 | bias = True, 31 | prior_sigma_1 = 0.1, 32 | prior_sigma_2 = 0.002, 33 | prior_pi = 1, 34 | posterior_mu_init = 0, 35 | posterior_rho_init = -6.0, 36 | freeze = False, 37 | prior_dist = None, 38 | peephole = False, 39 | **kwargs): 40 | 41 | super().__init__(**kwargs) 42 | self.in_features = in_features 43 | self.out_features = out_features 44 | self.use_bias = bias 45 | self.freeze = freeze 46 | self.peephole = peephole 47 | 48 | self.posterior_mu_init = posterior_mu_init 49 | self.posterior_rho_init = posterior_rho_init 50 | 51 | self.prior_sigma_1 = prior_sigma_1 52 | self.prior_sigma_2 = prior_sigma_2 53 | self.prior_pi = prior_pi 54 | self.prior_dist = prior_dist 55 | 56 | # Variational weight parameters and sample for weight ih 57 | self.weight_ih_mu = nn.Parameter(torch.Tensor(in_features, out_features * 4).normal_(posterior_mu_init, 0.1)) 58 | self.weight_ih_rho = nn.Parameter(torch.Tensor(in_features, out_features * 4).normal_(posterior_rho_init, 0.1)) 59 | self.weight_ih_sampler = TrainableRandomDistribution(self.weight_ih_mu, self.weight_ih_rho) 60 | self.weight_ih = None 61 | 62 | # Variational weight parameters and sample for weight hh 63 | self.weight_hh_mu = nn.Parameter(torch.Tensor(out_features, out_features * 4).normal_(posterior_mu_init, 0.1)) 64 | self.weight_hh_rho = nn.Parameter(torch.Tensor(out_features, out_features * 4).normal_(posterior_rho_init, 0.1)) 65 | self.weight_hh_sampler = TrainableRandomDistribution(self.weight_hh_mu, self.weight_hh_rho) 66 | self.weight_hh = None 67 | 68 | # Variational weight parameters and sample for bias 69 | self.bias_mu = nn.Parameter(torch.Tensor(out_features * 4).normal_(posterior_mu_init, 0.1)) 70 | self.bias_rho = nn.Parameter(torch.Tensor(out_features * 4).normal_(posterior_rho_init, 0.1)) 71 | self.bias_sampler = TrainableRandomDistribution(self.bias_mu, self.bias_rho) 72 | self.bias=None 73 | 74 | #our prior distributions 75 | self.weight_ih_prior_dist = PriorWeightDistribution(self.prior_pi, self.prior_sigma_1, self.prior_sigma_2, dist = self.prior_dist) 76 | self.weight_hh_prior_dist = PriorWeightDistribution(self.prior_pi, self.prior_sigma_1, self.prior_sigma_2, dist = self.prior_dist) 77 | self.bias_prior_dist = PriorWeightDistribution(self.prior_pi, self.prior_sigma_1, self.prior_sigma_2, dist = self.prior_dist) 78 | 79 | self.init_sharpen_parameters() 80 | 81 | self.log_prior = 0 82 | self.log_variational_posterior = 0 83 | 84 | 85 | def sample_weights(self): 86 | #sample weights 87 | weight_ih = self.weight_ih_sampler.sample() 88 | weight_hh = self.weight_hh_sampler.sample() 89 | 90 | #if use bias, we sample it, otherwise, we are using zeros 91 | if self.use_bias: 92 | b = self.bias_sampler.sample() 93 | b_log_posterior = self.bias_sampler.log_posterior() 94 | b_log_prior = self.bias_prior_dist.log_prior(b) 95 | 96 | else: 97 | b = None 98 | b_log_posterior = 0 99 | b_log_prior = 0 100 | 101 | bias = b 102 | 103 | #gather weights variational posterior and prior likelihoods 104 | self.log_variational_posterior = self.weight_hh_sampler.log_posterior() + b_log_posterior + self.weight_ih_sampler.log_posterior() 105 | 106 | self.log_prior = self.weight_ih_prior_dist.log_prior(weight_ih) + b_log_prior + self.weight_hh_prior_dist.log_prior(weight_hh) 107 | 108 | 109 | self.ff_parameters = [weight_ih, weight_hh, bias] 110 | return weight_ih, weight_hh, bias 111 | 112 | def get_frozen_weights(self): 113 | 114 | #get all deterministic weights 115 | weight_ih = self.weight_ih_mu 116 | weight_hh = self.weight_hh_mu 117 | if self.use_bias: 118 | bias = self.bias_mu 119 | else: 120 | bias = 0 121 | 122 | return weight_ih, weight_hh, bias 123 | 124 | 125 | def forward_(self, 126 | x, 127 | hidden_states, 128 | sharpen_loss): 129 | 130 | if self.loss_to_sharpen is not None: 131 | sharpen_loss = self.loss_to_sharpen 132 | weight_ih, weight_hh, bias = self.sharpen_posterior(loss=sharpen_loss, input_shape=x.shape) 133 | elif (sharpen_loss is not None): 134 | sharpen_loss = sharpen_loss 135 | weight_ih, weight_hh, bias = self.sharpen_posterior(loss=sharpen_loss, input_shape=x.shape) 136 | 137 | else: 138 | weight_ih, weight_hh, bias = self.sample_weights() 139 | 140 | #Assumes x is of shape (batch, sequence, feature) 141 | bs, seq_sz, _ = x.size() 142 | hidden_seq = [] 143 | 144 | #if no hidden state, we are using zeros 145 | if hidden_states is None: 146 | h_t, c_t = (torch.zeros(bs, self.out_features).to(x.device), 147 | torch.zeros(bs, self.out_features).to(x.device)) 148 | else: 149 | h_t, c_t = hidden_states 150 | 151 | #simplifying our out features, and hidden seq list 152 | HS = self.out_features 153 | hidden_seq = [] 154 | 155 | for t in range(seq_sz): 156 | x_t = x[:, t, :] 157 | # batch the computations into a single matrix multiplication 158 | 159 | if self.peephole: 160 | gates = x_t @ weight_ih + c_t @ weight_hh + bias 161 | else: 162 | gates = x_t @ weight_ih + h_t @ weight_hh + bias 163 | g_t = torch.tanh(gates[:, HS*2:HS*3]) 164 | 165 | i_t, f_t, o_t = ( 166 | torch.sigmoid(gates[:, :HS]), # input 167 | torch.sigmoid(gates[:, HS:HS*2]), # forget 168 | torch.sigmoid(gates[:, HS*3:]), # output 169 | ) 170 | 171 | if self.peephole: 172 | c_t = f_t * c_t + i_t * torch.sigmoid(x_t @ weight_ih + bias)[:, HS*2:HS*3] 173 | h_t = torch.tanh(o_t * c_t) 174 | else: 175 | c_t = f_t * c_t + i_t * g_t 176 | h_t = o_t * torch.tanh(c_t) 177 | 178 | hidden_seq.append(h_t.unsqueeze(0)) 179 | 180 | hidden_seq = torch.cat(hidden_seq, dim=0) 181 | # reshape from shape (sequence, batch, feature) to (batch, sequence, feature) 182 | hidden_seq = hidden_seq.transpose(0, 1).contiguous() 183 | 184 | return hidden_seq, (h_t, c_t) 185 | 186 | def forward_frozen(self, 187 | x, 188 | hidden_states): 189 | 190 | weight_ih, weight_hh, bias = self.get_frozen_weights() 191 | 192 | #Assumes x is of shape (batch, sequence, feature) 193 | bs, seq_sz, _ = x.size() 194 | hidden_seq = [] 195 | 196 | #if no hidden state, we are using zeros 197 | if hidden_states is None: 198 | h_t, c_t = (torch.zeros(bs, self.out_features).to(x.device), 199 | torch.zeros(bs, self.out_features).to(x.device)) 200 | else: 201 | h_t, c_t = hidden_states 202 | 203 | #simplifying our out features, and hidden seq list 204 | HS = self.out_features 205 | hidden_seq = [] 206 | 207 | for t in range(seq_sz): 208 | x_t = x[:, t, :] 209 | # batch the computations into a single matrix multiplication 210 | 211 | if self.peephole: 212 | gates = x_t @ weight_ih + c_t @ weight_hh + bias 213 | else: 214 | gates = x_t @ weight_ih + h_t @ weight_hh + bias 215 | g_t = torch.tanh(gates[:, HS*2:HS*3]) 216 | 217 | i_t, f_t, o_t = ( 218 | torch.sigmoid(gates[:, :HS]), # input 219 | torch.sigmoid(gates[:, HS:HS*2]), # forget 220 | torch.sigmoid(gates[:, HS*3:]), # output 221 | ) 222 | 223 | if self.peephole: 224 | c_t = f_t * c_t + i_t * torch.sigmoid(x_t @ weight_ih + bias)[:, HS*2:HS*3] 225 | h_t = torch.sigmoid(o_t * c_t) 226 | else: 227 | c_t = f_t * c_t + i_t * g_t 228 | h_t = o_t * torch.tanh(c_t) 229 | 230 | hidden_seq.append(h_t.unsqueeze(0)) 231 | 232 | hidden_seq = torch.cat(hidden_seq, dim=0) 233 | # reshape from shape (sequence, batch, feature) to (batch, sequence, feature) 234 | hidden_seq = hidden_seq.transpose(0, 1).contiguous() 235 | 236 | return hidden_seq, (h_t, c_t) 237 | 238 | def forward(self, 239 | x, 240 | hidden_states=None, 241 | sharpen_loss=None): 242 | 243 | if self.freeze: 244 | return self.forward_frozen(x, hidden_states) 245 | 246 | if not self.sharpen: 247 | sharpen_posterior = False 248 | 249 | return self.forward_(x, hidden_states, sharpen_loss) 250 | 251 | -------------------------------------------------------------------------------- /blitz/examples/cifar10_bvgg.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import os 3 | import shutil 4 | import time 5 | 6 | import torch 7 | import torch.nn as nn 8 | import torch.nn.parallel 9 | import torch.backends.cudnn as cudnn 10 | import torch.optim 11 | import torch.utils.data 12 | import torchvision.transforms as transforms 13 | import torchvision.datasets as datasets 14 | import blitz.models.b_vgg as vgg 15 | 16 | #adapted from https://github.com/chengyangfu/pytorch-vgg-cifar10/blob/master/main.py 17 | 18 | model_names = sorted(name for name in vgg.__dict__ 19 | if name.islower() and not name.startswith("__") 20 | and name.startswith("vgg") 21 | and callable(vgg.__dict__[name])) 22 | 23 | 24 | parser = argparse.ArgumentParser(description='PyTorch ImageNet Training') 25 | parser.add_argument('--arch', '-a', metavar='ARCH', default='vgg11_bn', 26 | choices=model_names, 27 | help='model architecture: ' + ' | '.join(model_names) + 28 | ' (default: vgg19)') 29 | parser.add_argument('-j', '--workers', default=4, type=int, metavar='N', 30 | help='number of data loading workers (default: 4)') 31 | parser.add_argument('--epochs', default=300, type=int, metavar='N', 32 | help='number of total epochs to run') 33 | parser.add_argument('--start-epoch', default=0, type=int, metavar='N', 34 | help='manual epoch number (useful on restarts)') 35 | parser.add_argument('-b', '--batch-size', default=128, type=int, 36 | metavar='N', help='mini-batch size (default: 128)') 37 | parser.add_argument('--lr', '--learning-rate', default=0.001, type=float, 38 | metavar='LR', help='initial learning rate') 39 | parser.add_argument('--print-freq', '-p', default=20, type=int, 40 | metavar='N', help='print frequency (default: 20)') 41 | parser.add_argument('--resume', default='', type=str, metavar='PATH', 42 | help='path to latest checkpoint (default: none)') 43 | parser.add_argument('-e', '--evaluate', dest='evaluate', action='store_true', 44 | help='evaluate model on validation set') 45 | parser.add_argument('--pretrained', dest='pretrained', action='store_true', 46 | help='use pre-trained model') 47 | parser.add_argument('--half', dest='half', action='store_true', 48 | help='use half-precision(16-bit) ') 49 | parser.add_argument('--cpu', dest='cpu', action='store_true', 50 | help='use cpu') 51 | parser.add_argument('--save-dir', dest='save_dir', 52 | help='The directory used to save the trained models', 53 | default='save_temp', type=str) 54 | 55 | 56 | best_prec1 = 0 57 | 58 | 59 | def main(): 60 | global args, best_prec1, freeze 61 | args = parser.parse_args() 62 | 63 | 64 | # Check the save_dir exists or not 65 | if not os.path.exists(args.save_dir): 66 | os.makedirs(args.save_dir) 67 | 68 | model = vgg.__dict__[args.arch]() 69 | 70 | model.features = torch.nn.DataParallel(model.features) 71 | if args.cpu: 72 | model.cpu() 73 | else: 74 | model.cuda() 75 | 76 | #model.freeze_() 77 | #freeze = True 78 | 79 | # optionally resume from a checkpoint 80 | if args.resume: 81 | if os.path.isfile(args.resume): 82 | print("=> loading checkpoint '{}'".format(args.resume)) 83 | checkpoint = torch.load(args.resume) 84 | args.start_epoch = checkpoint['epoch'] 85 | best_prec1 = checkpoint['best_prec1'] 86 | model.load_state_dict(checkpoint['state_dict']) 87 | print("=> loaded checkpoint '{}' (epoch {})" 88 | .format(args.evaluate, checkpoint['epoch'])) 89 | else: 90 | print("=> no checkpoint found at '{}'".format(args.resume)) 91 | 92 | cudnn.benchmark = True 93 | 94 | normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], 95 | std=[0.229, 0.224, 0.225]) 96 | 97 | train_loader = torch.utils.data.DataLoader( 98 | datasets.CIFAR10(root='./data', train=True, transform=transforms.Compose([ 99 | transforms.RandomHorizontalFlip(), 100 | transforms.RandomCrop(32, 4), 101 | transforms.ToTensor(), 102 | normalize, 103 | ]), download=True), 104 | batch_size=args.batch_size, shuffle=True, 105 | num_workers=args.workers, pin_memory=True) 106 | 107 | val_loader = torch.utils.data.DataLoader( 108 | datasets.CIFAR10(root='./data', train=False, transform=transforms.Compose([ 109 | transforms.ToTensor(), 110 | normalize, 111 | ])), 112 | batch_size=args.batch_size, shuffle=False, 113 | num_workers=args.workers, pin_memory=True) 114 | 115 | # define loss function (criterion) and pptimizer 116 | criterion = nn.CrossEntropyLoss() 117 | if args.cpu: 118 | criterion = criterion.cpu() 119 | else: 120 | criterion = criterion.cuda() 121 | 122 | if args.half: 123 | model.half() 124 | criterion.half() 125 | 126 | optimizer = torch.optim.Adam(model.parameters(), args.lr) 127 | 128 | if args.evaluate: 129 | validate(val_loader, model, criterion) 130 | return 131 | 132 | for epoch in range(args.start_epoch, args.epochs): 133 | adjust_learning_rate(optimizer, epoch) 134 | 135 | # train for one epoch 136 | train(train_loader, model, criterion, optimizer, epoch) 137 | 138 | # evaluate on validation set 139 | prec1 = validate(val_loader, model, criterion) 140 | 141 | # remember best prec@1 and save checkpoint 142 | is_best = prec1 > best_prec1 143 | best_prec1 = max(prec1, best_prec1) 144 | save_checkpoint({ 145 | 'epoch': epoch + 1, 146 | 'state_dict': model.state_dict(), 147 | 'best_prec1': best_prec1, 148 | }, is_best, filename=os.path.join(args.save_dir, 'checkpoint_{}.tar'.format(epoch))) 149 | 150 | 151 | def train(train_loader, model, criterion, optimizer, epoch): 152 | """ 153 | Run one train epoch 154 | """ 155 | global freeze 156 | 157 | batch_time = AverageMeter() 158 | data_time = AverageMeter() 159 | losses = AverageMeter() 160 | top1 = AverageMeter() 161 | 162 | # switch to train mode 163 | model.train() 164 | 165 | end = time.time() 166 | 167 | #if epoch == 3: 168 | # model.MOPED_() 169 | # freeze = False 170 | 171 | for i, (input, target) in enumerate(train_loader): 172 | 173 | # measure data loading time 174 | data_time.update(time.time() - end) 175 | 176 | if args.cpu == False: 177 | input = input.cuda() 178 | target = target.cuda() 179 | 180 | # compute output 181 | if not freeze: 182 | loss = model.sample_elbo(inputs=input, 183 | labels=target, 184 | criterion=criterion, 185 | sample_nbr=3, 186 | complexity_cost_weight=1/50000) 187 | else: 188 | output = model(input) 189 | loss = criterion(output, target) 190 | 191 | # compute gradient and do SGD step 192 | optimizer.zero_grad() 193 | loss.backward() 194 | optimizer.step() 195 | 196 | output = model(input) 197 | output = output.float() 198 | loss = loss.float() 199 | # measure accuracy and record loss 200 | prec1 = accuracy(output.data, target)[0] 201 | losses.update(loss.item(), input.size(0)) 202 | top1.update(prec1.item(), input.size(0)) 203 | 204 | # measure elapsed time 205 | batch_time.update(time.time() - end) 206 | end = time.time() 207 | 208 | if i % args.print_freq == 0: 209 | print('Epoch: [{0}][{1}/{2}]\t' 210 | 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t' 211 | 'Data {data_time.val:.3f} ({data_time.avg:.3f})\t' 212 | 'Loss {loss.val:.4f} ({loss.avg:.4f})\t' 213 | 'Prec@1 {top1.val:.3f} ({top1.avg:.3f})'.format( 214 | epoch, i, len(train_loader), batch_time=batch_time, 215 | data_time=data_time, loss=losses, top1=top1)) 216 | 217 | 218 | def validate(val_loader, model, criterion): 219 | """ 220 | Run evaluation 221 | """ 222 | batch_time = AverageMeter() 223 | losses = AverageMeter() 224 | top1 = AverageMeter() 225 | 226 | # switch to evaluate mode 227 | model.eval() 228 | 229 | end = time.time() 230 | for i, (input, target) in enumerate(val_loader): 231 | if args.cpu == False: 232 | input = input.cuda() 233 | target = target.cuda() 234 | 235 | if args.half: 236 | input = input.half() 237 | 238 | # compute output 239 | with torch.no_grad(): 240 | output = model(input) 241 | loss = criterion(output, target) 242 | 243 | output = output.float() 244 | loss = loss.float() 245 | 246 | # measure accuracy and record loss 247 | prec1 = accuracy(output.data, target)[0] 248 | losses.update(loss.item(), input.size(0)) 249 | top1.update(prec1.item(), input.size(0)) 250 | 251 | # measure elapsed time 252 | batch_time.update(time.time() - end) 253 | end = time.time() 254 | 255 | if i % args.print_freq == 0: 256 | print('Test: [{0}/{1}]\t' 257 | 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t' 258 | 'Loss {loss.val:.4f} ({loss.avg:.4f})\t' 259 | 'Prec@1 {top1.val:.3f} ({top1.avg:.3f})'.format( 260 | i, len(val_loader), batch_time=batch_time, loss=losses, 261 | top1=top1)) 262 | 263 | print(' * Prec@1 {top1.avg:.3f}' 264 | .format(top1=top1)) 265 | 266 | return top1.avg 267 | 268 | def save_checkpoint(state, is_best, filename='checkpoint.pth.tar'): 269 | """ 270 | Save the training model 271 | """ 272 | torch.save(state, filename) 273 | 274 | class AverageMeter(object): 275 | """Computes and stores the average and current value""" 276 | def __init__(self): 277 | self.reset() 278 | 279 | def reset(self): 280 | self.val = 0 281 | self.avg = 0 282 | self.sum = 0 283 | self.count = 0 284 | 285 | def update(self, val, n=1): 286 | self.val = val 287 | self.sum += val * n 288 | self.count += n 289 | self.avg = self.sum / self.count 290 | 291 | 292 | def adjust_learning_rate(optimizer, epoch): 293 | """Sets the learning rate to the initial LR decayed by 2 every 30 epochs""" 294 | lr = args.lr * (0.5 ** (epoch // 30)) 295 | for param_group in optimizer.param_groups: 296 | param_group['lr'] = lr 297 | 298 | 299 | def accuracy(output, target, topk=(1,)): 300 | """Computes the precision@k for the specified values of k""" 301 | maxk = max(topk) 302 | batch_size = target.size(0) 303 | 304 | _, pred = output.topk(maxk, 1, True, True) 305 | pred = pred.t() 306 | correct = pred.eq(target.view(1, -1).expand_as(pred)) 307 | 308 | res = [] 309 | for k in topk: 310 | correct_k = correct[:k].view(-1).float().sum(0) 311 | res.append(correct_k.mul_(100.0 / batch_size)) 312 | return res 313 | 314 | 315 | if __name__ == '__main__': 316 | freeze = False 317 | main() 318 | -------------------------------------------------------------------------------- /blitz/modules/tests/conv_bayesian_layer_test.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from blitz.modules import BayesianConv2d, BayesianConv1d, BayesianConv3d 3 | from blitz.modules.base_bayesian_module import BayesianModule 4 | 5 | import torch 6 | from torch import nn 7 | 8 | class TestConv1DBayesian(unittest.TestCase): 9 | 10 | def test_init_bayesian_layer(self): 11 | #create bayesian layer 12 | 13 | module = BayesianConv1d(3, 10, 3) 14 | pass 15 | 16 | def test_weights_shape(self): 17 | #check if weights shape is the expected 18 | bconv = BayesianConv1d(in_channels=3, 19 | out_channels=3, 20 | kernel_size=3) 21 | 22 | conv = nn.Conv1d(in_channels=3, 23 | out_channels=3, 24 | kernel_size=3) 25 | 26 | to_feed = torch.ones((1, 3, 25)) 27 | 28 | infer1 = bconv(to_feed) 29 | infer2 = conv(to_feed) 30 | 31 | self.assertEqual(infer1.shape, infer2.shape) 32 | pass 33 | 34 | def test_weights_shape_cuda(self): 35 | #check if weights shape is the expected 36 | device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') 37 | bconv = BayesianConv1d(in_channels=3, 38 | out_channels=3, 39 | kernel_size=3).to(device) 40 | 41 | conv = nn.Conv1d(in_channels=3, 42 | out_channels=3, 43 | kernel_size=3).to(device) 44 | 45 | to_feed = torch.ones((1, 3, 25)).to(device) 46 | 47 | infer1 = bconv(to_feed) 48 | infer2 = conv(to_feed) 49 | 50 | self.assertEqual(infer1.shape, infer2.shape) 51 | pass 52 | 53 | def test_variational_inference(self): 54 | #create module, check if inference is variating 55 | bconv = BayesianConv1d(in_channels=3, 56 | out_channels=3, 57 | kernel_size=1) 58 | 59 | conv = nn.Conv1d(in_channels=3, 60 | out_channels=3, 61 | kernel_size=3) 62 | 63 | to_feed = torch.ones((1, 3, 25)) 64 | 65 | self.assertEqual((bconv(to_feed) != bconv(to_feed)).any(), torch.tensor(True)) 66 | self.assertEqual((conv(to_feed) == conv(to_feed)).all(), torch.tensor(True)) 67 | pass 68 | 69 | 70 | def test_freeze_module(self): 71 | #create module, freeze 72 | #check if two inferences keep equal 73 | bconv = BayesianConv1d(in_channels=3, 74 | out_channels=3, 75 | kernel_size=3, 76 | bias=False) 77 | 78 | to_feed = torch.ones((1, 3, 25)) 79 | 80 | self.assertEqual((bconv(to_feed) != bconv(to_feed)).any(), torch.tensor(True)) 81 | 82 | frozen_feedforward = bconv.forward_frozen(to_feed) 83 | bconv.freeze = True 84 | self.assertEqual((bconv.forward(to_feed) == frozen_feedforward).all(), torch.tensor(True)) 85 | pass 86 | 87 | def test_inheritance(self): 88 | 89 | #check if bayesian linear has nn.Module and BayesianModule classes 90 | bconv = BayesianConv1d(in_channels=3, 91 | out_channels=3, 92 | kernel_size=3, 93 | bias=False) 94 | 95 | self.assertEqual(isinstance(bconv, (nn.Module)), True) 96 | self.assertEqual(isinstance(bconv, (BayesianModule)), True) 97 | 98 | def test_kl_divergence(self): 99 | #create model, sample weights 100 | #check if kl divergence between apriori and a posteriori is working 101 | bconv = BayesianConv1d(in_channels=3, 102 | out_channels=3, 103 | kernel_size=3) 104 | 105 | to_feed = torch.ones((1, 3, 25)) 106 | predicted = bconv(to_feed) 107 | 108 | complexity_cost = bconv.log_variational_posterior - bconv.log_prior 109 | self.assertEqual((complexity_cost == complexity_cost).all(), torch.tensor(True)) 110 | pass 111 | 112 | class TestConv2DBayesian(unittest.TestCase): 113 | 114 | def test_init_bayesian_layer(self): 115 | #create bayesian layer 116 | 117 | module = BayesianConv2d(3, 10, (3,3)) 118 | pass 119 | 120 | def test_weights_shape(self): 121 | #check if weights shape is the expected 122 | bconv = BayesianConv2d(in_channels=3, 123 | out_channels=3, 124 | kernel_size=(3,3)) 125 | 126 | conv = nn.Conv2d(in_channels=3, 127 | out_channels=3, 128 | kernel_size=(3,3)) 129 | 130 | to_feed = torch.ones((1, 3, 25, 25)) 131 | 132 | infer1 = bconv(to_feed) 133 | infer2 = conv(to_feed) 134 | 135 | self.assertEqual(infer1.shape, infer2.shape) 136 | pass 137 | 138 | def test_weights_shape_cuda(self): 139 | #check if weights shape is the expected 140 | device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') 141 | bconv = BayesianConv2d(in_channels=3, 142 | out_channels=3, 143 | kernel_size=(3,3)).to(device) 144 | 145 | conv = nn.Conv2d(in_channels=3, 146 | out_channels=3, 147 | kernel_size=(3,3)).to(device) 148 | 149 | to_feed = torch.ones((1, 3, 25, 25)).to(device) 150 | 151 | infer1 = bconv(to_feed) 152 | infer2 = conv(to_feed) 153 | 154 | self.assertEqual(infer1.shape, infer2.shape) 155 | pass 156 | 157 | def test_variational_inference(self): 158 | #create module, check if inference is variating 159 | bconv = BayesianConv2d(in_channels=3, 160 | out_channels=3, 161 | kernel_size=(3,3)) 162 | 163 | conv = nn.Conv2d(in_channels=3, 164 | out_channels=3, 165 | kernel_size=(3,3)) 166 | 167 | to_feed = torch.ones((1, 3, 25, 25)) 168 | 169 | self.assertEqual((bconv(to_feed) != bconv(to_feed)).any(), torch.tensor(True)) 170 | self.assertEqual((conv(to_feed) == conv(to_feed)).all(), torch.tensor(True)) 171 | pass 172 | 173 | 174 | def test_freeze_module(self): 175 | #create module, freeze 176 | #check if two inferences keep equal 177 | bconv = BayesianConv2d(in_channels=3, 178 | out_channels=3, 179 | kernel_size=(3,3), 180 | bias=False) 181 | 182 | to_feed = torch.ones((1, 3, 25, 25)) 183 | 184 | self.assertEqual((bconv(to_feed) != bconv(to_feed)).any(), torch.tensor(True)) 185 | 186 | frozen_feedforward = bconv.forward_frozen(to_feed) 187 | bconv.freeze = True 188 | self.assertEqual((bconv.forward(to_feed) == frozen_feedforward).all(), torch.tensor(True)) 189 | pass 190 | 191 | def test_inheritance(self): 192 | 193 | #check if bayesian linear has nn.Module and BayesianModule classes 194 | bconv = BayesianConv2d(in_channels=3, 195 | out_channels=3, 196 | kernel_size=(3,3), 197 | bias=False) 198 | 199 | self.assertEqual(isinstance(bconv, (nn.Module)), True) 200 | self.assertEqual(isinstance(bconv, (BayesianModule)), True) 201 | 202 | def test_kl_divergence(self): 203 | #create model, sample weights 204 | #check if kl divergence between apriori and a posteriori is working 205 | bconv = BayesianConv2d(in_channels=3, 206 | out_channels=3, 207 | kernel_size=(3,3)) 208 | 209 | to_feed = torch.ones((1, 3, 25, 25)) 210 | predicted = bconv(to_feed) 211 | 212 | complexity_cost = bconv.log_variational_posterior - bconv.log_prior 213 | self.assertEqual((complexity_cost == complexity_cost).all(), torch.tensor(True)) 214 | pass 215 | class TestConv3DBayesian(unittest.TestCase): 216 | 217 | def test_init_bayesian_layer(self): 218 | #create bayesian layer 219 | 220 | module = BayesianConv3d(3, 10, (3,3, 3)) 221 | pass 222 | 223 | def test_weights_shape(self): 224 | #check if weights shape is the expected 225 | bconv = BayesianConv3d(in_channels=3, 226 | out_channels=3, 227 | kernel_size=(3,3,3)) 228 | 229 | conv = nn.Conv3d(in_channels=3, 230 | out_channels=3, 231 | kernel_size=(3,3,3)) 232 | 233 | to_feed = torch.ones((1, 3, 25, 25, 25)) 234 | 235 | infer1 = bconv(to_feed) 236 | infer2 = conv(to_feed) 237 | 238 | self.assertEqual(infer1.shape, infer2.shape) 239 | pass 240 | 241 | def test_weights_shape_cuda(self): 242 | #check if weights shape is the expected 243 | device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') 244 | bconv = BayesianConv3d(in_channels=3, 245 | out_channels=3, 246 | kernel_size=(3,3,3)).to(device) 247 | 248 | conv = nn.Conv3d(in_channels=3, 249 | out_channels=3, 250 | kernel_size=(3,3,3)).to(device) 251 | 252 | to_feed = torch.ones((1, 3, 25, 25, 25)).to(device) 253 | 254 | infer1 = bconv(to_feed) 255 | infer2 = conv(to_feed) 256 | 257 | self.assertEqual(infer1.shape, infer2.shape) 258 | pass 259 | 260 | def test_variational_inference(self): 261 | #create module, check if inference is variating 262 | bconv = BayesianConv3d(in_channels=3, 263 | out_channels=3, 264 | kernel_size=(3,3,3)) 265 | 266 | conv = nn.Conv3d(in_channels=3, 267 | out_channels=3, 268 | kernel_size=(3,3,3)) 269 | 270 | to_feed = torch.ones((1, 3, 25, 25,25)) 271 | 272 | self.assertEqual((bconv(to_feed) != bconv(to_feed)).any(), torch.tensor(True)) 273 | self.assertEqual((conv(to_feed) == conv(to_feed)).all(), torch.tensor(True)) 274 | pass 275 | 276 | 277 | def test_freeze_module(self): 278 | #create module, freeze 279 | #check if two inferences keep equal 280 | bconv = BayesianConv3d(in_channels=3, 281 | out_channels=3, 282 | kernel_size=(3,3,3), 283 | bias=False) 284 | 285 | to_feed = torch.ones((1, 3, 25, 25,25)) 286 | 287 | self.assertEqual((bconv(to_feed) != bconv(to_feed)).any(), torch.tensor(True)) 288 | 289 | frozen_feedforward = bconv.forward_frozen(to_feed) 290 | bconv.freeze = True 291 | self.assertEqual((bconv.forward(to_feed) == frozen_feedforward).all(), torch.tensor(True)) 292 | pass 293 | 294 | def test_inheritance(self): 295 | 296 | #check if bayesian linear has nn.Module and BayesianModule classes 297 | bconv = BayesianConv3d(in_channels=3, 298 | out_channels=3, 299 | kernel_size=(3,3,3), 300 | bias=False) 301 | 302 | self.assertEqual(isinstance(bconv, (nn.Module)), True) 303 | self.assertEqual(isinstance(bconv, (BayesianModule)), True) 304 | 305 | def test_kl_divergence(self): 306 | #create model, sample weights 307 | #check if kl divergence between apriori and a posteriori is working 308 | bconv = BayesianConv3d(in_channels=3, 309 | out_channels=3, 310 | kernel_size=(3,3,3)) 311 | 312 | to_feed = torch.ones((1, 3, 25, 25,25)) 313 | predicted = bconv(to_feed) 314 | 315 | complexity_cost = bconv.log_variational_posterior - bconv.log_prior 316 | self.assertEqual((complexity_cost == complexity_cost).all(), torch.tensor(True)) 317 | pass 318 | 319 | if __name__ == "__main__": 320 | unittest.main() -------------------------------------------------------------------------------- /blitz/modules/conv_bayesian_layer.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import torch 3 | from torch import nn 4 | from torch.nn import functional as F 5 | 6 | from blitz.modules.base_bayesian_module import BayesianModule 7 | from blitz.modules.weight_sampler import TrainableRandomDistribution, PriorWeightDistribution 8 | 9 | class BayesianConv1d(BayesianModule): 10 | 11 | # Implements Bayesian Conv2d layer, by drawing them using Weight Uncertanity on Neural Networks algorithm 12 | """ 13 | Bayesian Linear layer, implements a Convolution 1D layer as proposed on Weight Uncertainity on Neural Networks 14 | (Bayes by Backprop paper). 15 | 16 | Its objective is be interactable with torch nn.Module API, being able even to be chained in nn.Sequential models with other non-this-lib layers 17 | 18 | parameters: 19 | in_channels: int -> incoming channels for the layer 20 | out_channels: int -> output channels for the layer 21 | kernel_size : tuple (int, int) -> size of the kernels for this convolution layer 22 | groups : int -> number of groups on which the convolutions will happend 23 | padding : int -> size of padding (0 if no padding) 24 | dilation int -> dilation of the weights applied on the input tensor 25 | 26 | 27 | bias: bool -> whether the bias will exist (True) or set to zero (False) 28 | prior_sigma_1: float -> prior sigma on the mixture prior distribution 1 29 | prior_sigma_2: float -> prior sigma on the mixture prior distribution 2 30 | prior_pi: float -> pi on the scaled mixture prior 31 | posterior_mu_init float -> posterior mean for the weight mu init 32 | posterior_rho_init float -> posterior mean for the weight rho init 33 | freeze: bool -> wheter the model will start with frozen(deterministic) weights, or not 34 | 35 | """ 36 | def __init__(self, 37 | in_channels, 38 | out_channels, 39 | kernel_size, 40 | groups = 1, 41 | stride = 1, 42 | padding = 0, 43 | dilation = 1, 44 | bias=True, 45 | prior_sigma_1 = 0.1, 46 | prior_sigma_2 = 0.002, 47 | prior_pi = 1, 48 | posterior_mu_init = 0, 49 | posterior_rho_init = -7.0, 50 | freeze = False, 51 | prior_dist = None): 52 | super().__init__() 53 | 54 | #our main parameters 55 | self.in_channels = in_channels 56 | self.out_channels = out_channels 57 | self.freeze = freeze 58 | self.kernel_size = kernel_size 59 | self.groups = groups 60 | self.stride = stride 61 | self.padding = padding 62 | self.dilation = dilation 63 | self.bias = bias 64 | 65 | 66 | self.posterior_mu_init = posterior_mu_init 67 | self.posterior_rho_init = posterior_rho_init 68 | 69 | #parameters for the scale mixture prior 70 | self.prior_sigma_1 = prior_sigma_1 71 | self.prior_sigma_2 = prior_sigma_2 72 | self.prior_pi = prior_pi 73 | self.prior_dist = prior_dist 74 | 75 | #our weights 76 | self.weight_mu = nn.Parameter(torch.Tensor(out_channels, in_channels // groups, kernel_size).normal_(posterior_mu_init, 0.1)) 77 | self.weight_rho = nn.Parameter(torch.Tensor(out_channels, in_channels // groups, kernel_size).normal_(posterior_rho_init, 0.1)) 78 | self.weight_sampler = TrainableRandomDistribution(self.weight_mu, self.weight_rho) 79 | 80 | #our biases 81 | if self.bias: 82 | self.bias_mu = nn.Parameter(torch.Tensor(out_channels).normal_(posterior_mu_init, 0.1)) 83 | self.bias_rho = nn.Parameter(torch.Tensor(out_channels).normal_(posterior_rho_init, 0.1)) 84 | self.bias_sampler = TrainableRandomDistribution(self.bias_mu, self.bias_rho) 85 | self.bias_prior_dist = PriorWeightDistribution(self.prior_pi, self.prior_sigma_1, self.prior_sigma_2, dist = self.prior_dist) 86 | else: 87 | self.register_buffer('bias_zero', torch.zeros((self.out_channels)) ) 88 | 89 | # Priors (as BBP paper) 90 | self.weight_prior_dist = PriorWeightDistribution(self.prior_pi, self.prior_sigma_1, self.prior_sigma_2, dist = self.prior_dist) 91 | self.bias_prior_dist = PriorWeightDistribution(self.prior_pi, self.prior_sigma_1, self.prior_sigma_2, dist = self.prior_dist) 92 | self.log_prior = 0 93 | self.log_variational_posterior = 0 94 | 95 | def forward(self, x): 96 | #Forward with uncertain weights, fills bias with zeros if layer has no bias 97 | #Also calculates the complecity cost for this sampling 98 | if self.freeze: 99 | return self.forward_frozen(x) 100 | 101 | w = self.weight_sampler.sample() 102 | 103 | if self.bias: 104 | b = self.bias_sampler.sample() 105 | b_log_posterior = self.bias_sampler.log_posterior() 106 | b_log_prior = self.bias_prior_dist.log_prior(b) 107 | 108 | else: 109 | b = self.bias_zero 110 | b_log_posterior = 0 111 | b_log_prior = 0 112 | 113 | self.log_variational_posterior = self.weight_sampler.log_posterior() + b_log_posterior 114 | self.log_prior = self.weight_prior_dist.log_prior(w) + b_log_prior 115 | 116 | return F.conv1d(input=x, 117 | weight=w, 118 | bias=b, 119 | stride=self.stride, 120 | padding=self.padding, 121 | dilation=self.dilation, 122 | groups=self.groups) 123 | 124 | def forward_frozen(self, x): 125 | # Computes the feedforward operation with the expected value for weight and biases (frozen-like) 126 | 127 | if self.bias: 128 | bias = self.bias_mu 129 | assert bias is self.bias_mu, "The bias inputed should be this layer parameter, not a clone." 130 | else: 131 | bias = self.bias_zero 132 | 133 | return F.conv1d(input=x, 134 | weight=self.weight_mu, 135 | bias=bias, 136 | stride=self.stride, 137 | padding=self.padding, 138 | dilation=self.dilation, 139 | groups=self.groups) 140 | 141 | class BayesianConv2d(BayesianModule): 142 | 143 | # Implements Bayesian Conv2d layer, by drawing them using Weight Uncertanity on Neural Networks algorithm 144 | """ 145 | Bayesian Linear layer, implements a Convolution 2D layer as proposed on Weight Uncertainity on Neural Networks 146 | (Bayes by Backprop paper). 147 | 148 | Its objective is be interactable with torch nn.Module API, being able even to be chained in nn.Sequential models with other non-this-lib layers 149 | 150 | parameters: 151 | in_channels: int -> incoming channels for the layer 152 | out_channels: int -> output channels for the layer 153 | kernel_size : tuple (int, int) -> size of the kernels for this convolution layer 154 | groups : int -> number of groups on which the convolutions will happend 155 | padding : int -> size of padding (0 if no padding) 156 | dilation int -> dilation of the weights applied on the input tensor 157 | 158 | 159 | bias: bool -> whether the bias will exist (True) or set to zero (False) 160 | prior_sigma_1: float -> prior sigma on the mixture prior distribution 1 161 | prior_sigma_2: float -> prior sigma on the mixture prior distribution 2 162 | prior_pi: float -> pi on the scaled mixture prior 163 | posterior_mu_init float -> posterior mean for the weight mu init 164 | posterior_rho_init float -> posterior mean for the weight rho init 165 | freeze: bool -> wheter the model will start with frozen(deterministic) weights, or not 166 | 167 | """ 168 | def __init__(self, 169 | in_channels, 170 | out_channels, 171 | kernel_size, 172 | groups = 1, 173 | stride = 1, 174 | padding = 0, 175 | dilation = 1, 176 | bias=True, 177 | prior_sigma_1 = 0.1, 178 | prior_sigma_2 = 0.002, 179 | prior_pi = 1, 180 | posterior_mu_init = 0, 181 | posterior_rho_init = -6.0, 182 | freeze = False, 183 | prior_dist = None): 184 | super().__init__() 185 | 186 | #our main parameters 187 | self.in_channels = in_channels 188 | self.out_channels = out_channels 189 | self.freeze = freeze 190 | self.kernel_size = kernel_size 191 | self.groups = groups 192 | self.stride = stride 193 | self.padding = padding 194 | self.dilation = dilation 195 | self.bias = bias 196 | 197 | 198 | self.posterior_mu_init = posterior_mu_init 199 | self.posterior_rho_init = posterior_rho_init 200 | 201 | #parameters for the scale mixture prior 202 | self.prior_sigma_1 = prior_sigma_1 203 | self.prior_sigma_2 = prior_sigma_2 204 | self.prior_pi = prior_pi 205 | self.prior_dist = prior_dist 206 | 207 | #our weights 208 | self.weight_mu = nn.Parameter(torch.Tensor(out_channels, in_channels // groups, *kernel_size).normal_(posterior_mu_init, 0.1)) 209 | self.weight_rho = nn.Parameter(torch.Tensor(out_channels, in_channels // groups, *kernel_size).normal_(posterior_rho_init, 0.1)) 210 | self.weight_sampler = TrainableRandomDistribution(self.weight_mu, self.weight_rho) 211 | 212 | #our biases 213 | if self.bias: 214 | self.bias_mu = nn.Parameter(torch.Tensor(out_channels).normal_(posterior_mu_init, 0.1)) 215 | self.bias_rho = nn.Parameter(torch.Tensor(out_channels).normal_(posterior_rho_init, 0.1)) 216 | self.bias_sampler = TrainableRandomDistribution(self.bias_mu, self.bias_rho) 217 | self.bias_prior_dist = PriorWeightDistribution(self.prior_pi, self.prior_sigma_1, self.prior_sigma_2, dist = self.prior_dist) 218 | else: 219 | self.register_buffer('bias_zero', torch.zeros((self.out_channels)) ) 220 | 221 | # Priors (as BBP paper) 222 | self.weight_prior_dist = PriorWeightDistribution(self.prior_pi, self.prior_sigma_1, self.prior_sigma_2, dist = self.prior_dist) 223 | self.log_prior = 0 224 | self.log_variational_posterior = 0 225 | 226 | def forward(self, x): 227 | #Forward with uncertain weights, fills bias with zeros if layer has no bias 228 | #Also calculates the complecity cost for this sampling 229 | if self.freeze: 230 | return self.forward_frozen(x) 231 | 232 | w = self.weight_sampler.sample() 233 | 234 | if self.bias: 235 | b = self.bias_sampler.sample() 236 | b_log_posterior = self.bias_sampler.log_posterior() 237 | b_log_prior = self.bias_prior_dist.log_prior(b) 238 | 239 | else: 240 | b = self.bias_zero 241 | b_log_posterior = 0 242 | b_log_prior = 0 243 | 244 | self.log_variational_posterior = self.weight_sampler.log_posterior() + b_log_posterior 245 | self.log_prior = self.weight_prior_dist.log_prior(w) + b_log_prior 246 | 247 | return F.conv2d(input=x, 248 | weight=w, 249 | bias=b, 250 | stride=self.stride, 251 | padding=self.padding, 252 | dilation=self.dilation, 253 | groups=self.groups) 254 | 255 | def forward_frozen(self, x): 256 | # Computes the feedforward operation with the expected value for weight and biases (frozen-like) 257 | 258 | if self.bias: 259 | bias = self.bias_mu 260 | assert bias is self.bias_mu, "The bias inputed should be this layer parameter, not a clone." 261 | else: 262 | bias = self.bias_zero 263 | 264 | return F.conv2d(input=x, 265 | weight=self.weight_mu, 266 | bias=bias, 267 | stride=self.stride, 268 | padding=self.padding, 269 | dilation=self.dilation, 270 | groups=self.groups) 271 | 272 | class BayesianConv3d(BayesianModule): 273 | 274 | # Implements Bayesian Conv2d layer, by drawing them using Weight Uncertanity on Neural Networks algorithm 275 | """ 276 | Bayesian Linear layer, implements a Convolution 3D layer as proposed on Weight Uncertainity on Neural Networks 277 | (Bayes by Backprop paper). 278 | 279 | Its objective is be interactable with torch nn.Module API, being able even to be chained in nn.Sequential models with other non-this-lib layers 280 | 281 | parameters: 282 | in_channels: int -> incoming channels for the layer 283 | out_channels: int -> output channels for the layer 284 | kernel_size : tuple (int, int) -> size of the kernels for this convolution layer 285 | groups : int -> number of groups on which the convolutions will happend 286 | padding : int -> size of padding (0 if no padding) 287 | dilation int -> dilation of the weights applied on the input tensor 288 | 289 | 290 | bias: bool -> whether the bias will exist (True) or set to zero (False) 291 | prior_sigma_1: float -> prior sigma on the mixture prior distribution 1 292 | prior_sigma_2: float -> prior sigma on the mixture prior distribution 2 293 | prior_pi: float -> pi on the scaled mixture prior 294 | posterior_mu_init float -> posterior mean for the weight mu init 295 | posterior_rho_init float -> posterior mean for the weight rho init 296 | freeze: bool -> wheter the model will start with frozen(deterministic) weights, or not 297 | 298 | """ 299 | def __init__(self, 300 | in_channels, 301 | out_channels, 302 | kernel_size, 303 | groups = 1, 304 | stride = 1, 305 | padding = 0, 306 | dilation = 1, 307 | bias=True, 308 | prior_sigma_1 = 0.1, 309 | prior_sigma_2 = 0.002, 310 | prior_pi = 1, 311 | posterior_mu_init = 0, 312 | posterior_rho_init = -6.0, 313 | freeze = False, 314 | prior_dist = None): 315 | super().__init__() 316 | 317 | #our main parameters 318 | self.in_channels = in_channels 319 | self.out_channels = out_channels 320 | self.freeze = freeze 321 | self.kernel_size = kernel_size 322 | self.groups = groups 323 | self.stride = stride 324 | self.padding = padding 325 | self.dilation = dilation 326 | self.bias = bias 327 | 328 | 329 | self.posterior_mu_init = posterior_mu_init 330 | self.posterior_rho_init = posterior_rho_init 331 | 332 | #parameters for the scale mixture prior 333 | self.prior_sigma_1 = prior_sigma_1 334 | self.prior_sigma_2 = prior_sigma_2 335 | self.prior_pi = prior_pi 336 | self.prior_dist = prior_dist 337 | 338 | #our weights 339 | self.weight_mu = nn.Parameter(torch.Tensor(out_channels, in_channels // groups, *kernel_size).normal_(posterior_mu_init, 0.1)) 340 | self.weight_rho = nn.Parameter(torch.Tensor(out_channels, in_channels // groups, *kernel_size).normal_(posterior_rho_init, 0.1)) 341 | self.weight_sampler = TrainableRandomDistribution(self.weight_mu, self.weight_rho) 342 | 343 | #our biases 344 | if self.bias: 345 | self.bias_mu = nn.Parameter(torch.Tensor(out_channels).normal_(posterior_mu_init, 0.1)) 346 | self.bias_rho = nn.Parameter(torch.Tensor(out_channels).normal_(posterior_rho_init, 0.1)) 347 | self.bias_sampler = TrainableRandomDistribution(self.bias_mu, self.bias_rho) 348 | self.bias_prior_dist = PriorWeightDistribution(self.prior_pi, self.prior_sigma_1, self.prior_sigma_2, dist = self.prior_dist) 349 | else: 350 | self.register_buffer('bias_zero', torch.zeros((self.out_channels)) ) 351 | 352 | # Priors (as BBP paper) 353 | self.weight_prior_dist = PriorWeightDistribution(self.prior_pi, self.prior_sigma_1, self.prior_sigma_2, dist = self.prior_dist) 354 | self.log_prior = 0 355 | self.log_variational_posterior = 0 356 | 357 | def forward(self, x): 358 | #Forward with uncertain weights, fills bias with zeros if layer has no bias 359 | #Also calculates the complecity cost for this sampling 360 | if self.freeze: 361 | return self.forward_frozen(x) 362 | 363 | w = self.weight_sampler.sample() 364 | 365 | if self.bias: 366 | b = self.bias_sampler.sample() 367 | b_log_posterior = self.bias_sampler.log_posterior() 368 | b_log_prior = self.bias_prior_dist.log_prior(b) 369 | 370 | else: 371 | b = self.bias_zero 372 | b_log_posterior = 0 373 | b_log_prior = 0 374 | 375 | self.log_variational_posterior = self.weight_sampler.log_posterior() + b_log_posterior 376 | self.log_prior = self.weight_prior_dist.log_prior(w) + b_log_prior 377 | 378 | return F.conv3d(input=x, 379 | weight=w, 380 | bias=b, 381 | stride=self.stride, 382 | padding=self.padding, 383 | dilation=self.dilation, 384 | groups=self.groups) 385 | 386 | def forward_frozen(self, x): 387 | # Computes the feedforward operation with the expected value for weight and biases (frozen-like) 388 | 389 | if self.bias: 390 | bias = self.bias_mu 391 | assert bias is self.bias_mu, "The bias inputed should be this layer parameter, not a clone." 392 | else: 393 | bias = self.bias_zero 394 | 395 | return F.conv3d(input=x, 396 | weight=self.weight_mu, 397 | bias=bias, 398 | stride=self.stride, 399 | padding=self.padding, 400 | dilation=self.dilation, 401 | groups=self.groups) 402 | -------------------------------------------------------------------------------- /doc/layers.md: -------------------------------------------------------------------------------- 1 | # Bayesian Neural Network layers 2 | They all inherit from torch.nn.Module 3 | # Index: 4 | * [BayesianModule](#class-BayesianModule) 5 | * [BayesianLinear](#class-BayesianLinear) 6 | * [BayesianConv1d](#class-BayesianConv1d) 7 | * [BayesianConv2d](#class-BayesianConv2d) 8 | * [BayesianConv3d](#class-BayesianConv3d) 9 | * [BayesianLSTM](#class-BayesianLSTM) 10 | * [BayesianGRU](#class-BayesianGRU) 11 | * [BayesianEmbedding](#class-BayesianEmbedding) 12 | 13 | --- 14 | ## class BayesianModule(torch.nn.Module) 15 | ### blitz.modules.base_bayesian_module.BayesianModule() 16 | Implements a as-interface used BayesianModule to enable further specific behavior 17 | Inherits from torch.nn.Module 18 | 19 | --- 20 | 21 | ## class BayesianLinear 22 | ### blitz.modules.BayesianLinear(in_features, out_features, bias=True, prior_sigma_1 = 1, prior_sigma_2 = 0.002, prior_pi = 0.5, freeze = False) 23 | 24 | Bayesian Linear layer, implements the linear layer proposed on Weight Uncertainity on Neural Networks (Bayes by Backprop paper). 25 | 26 | Creates weight samplers of the class TrainableRandomDistribution for the weights and biases to be used on its feedforward ops. 27 | 28 | Inherits from BayesianModule 29 | 30 | #### Parameters: 31 | * in_features int -> Number nodes of the information to be feedforwarded 32 | * out_features int -> Number of out nodes of the layer 33 | * bias bool -> wheter the model will have biases 34 | * prior_sigma_1 float -> sigma of one of the prior w distributions to mixture 35 | * prior_sigma_2 float -> sigma of one of the prior w distributions to mixture 36 | * prior_pi float -> factor to scale the gaussian mixture of the model prior distribution 37 | * freeze -> wheter the model is instaced as frozen (will use deterministic weights on the feedforward op) 38 | * posterior_mu_init float -> posterior mean for the weight mu init 39 | * posterior_rho_init float -> posterior mean for the weight rho init 40 | * prior_dist -> torch.distributions.distribution.Distribution corresponding to a prior distribution different than a normal / scale mixture normal; if you pass that, the prior distribution will be that one and prior_sigma1 and prior_sigma2 and prior_pi can be dismissed. - Note that there is a torch issue that may output you logprob as NaN, so beware of the prior dist you are using. 41 | 42 | #### Methods: 43 | * forward(): 44 | 45 | Performs a feedforward operation with sampled weights. If the model is frozen uses only the expected values. 46 | 47 | Returns torch.tensor 48 | 49 | Description 50 | ##### Parameters 51 | * x - torch.tensor corresponding to the datapoints tensor to be feedforwarded 52 | 53 | * forward_frozen(x): 54 | 55 | Performs a feedforward operation using onle the mu tensor as weights. 56 | 57 | Returns torch.tensor 58 | 59 | Description 60 | ##### Parameters 61 | * x = torch.tensor corresponding to the datapoints tensor to be feedforwarded 62 | 63 | --- 64 | ## class BayesianConv1d 65 | ### blitz.modules.BayesianConv1d(in_channels, out_channels, kernel_size, groups = 1, stride = 1, padding = 0, dilation = 1, bias=True, prior_sigma_1 = 1, prior_sigma_2 = 0.002, prior_pi = 0.5, freeze = False) 66 | DESCRIPTION 67 | 68 | #### Parameters: 69 | * in_channels int -> incoming channels for the layer 70 | * out_channels int -> output channels for the layer 71 | * kernel_size int -> size of the kernels for this convolution layer 72 | * groups int -> number of groups on which the convolutions will happend 73 | * padding int -> size of padding (0 if no padding) 74 | * dilation int -> dilation of the weights applied on the input tensor 75 | * bias bool -> whether the bias will exist (True) or set to zero (False) 76 | * prior_sigma_1 float -> prior sigma on the mixture prior distribution 1 77 | * prior_sigma_2 float -> prior sigma on the mixture prior distribution 2 78 | * prior_pi float -> pi on the scaled mixture prior 79 | * posterior_mu_init float -> posterior mean for the weight mu init 80 | * posterior_rho_init float -> posterior mean for the weight rho init 81 | * freeze bool -> wheter the model will start with frozen(deterministic) weights, or not 82 | * prior_dist -> torch.distributions.distribution.Distribution corresponding to a prior distribution different than a normal / scale mixture normal; if you pass that, the prior distribution will be that one and prior_sigma1 and prior_sigma2 and prior_pi can be dismissed. - Note that there is a torch issue that may output you logprob as NaN, so beware of the prior dist you are using. 83 | 84 | #### Methods: 85 | * forward(): 86 | 87 | Performs a feedforward Conv3d operation with sampled weights. If the model is frozen uses only the expected values. 88 | 89 | Returns torch.tensor 90 | 91 | Description 92 | ##### Parameters 93 | * x - torch.tensor corresponding to the datapoints tensor to be feedforwarded 94 | 95 | * forward_frozen(x): 96 | 97 | Performs a feedforward Conv2d operation using onle the mu tensor as weights. 98 | 99 | Returns torch.tensor 100 | 101 | Description 102 | ##### Parameters 103 | * x = torch.tensor corresponding to the datapoints tensor to be feedforwarded 104 | 105 | 106 | --- 107 | 108 | ## class BayesianConv2d 109 | ### blitz.modules.BayesianConv2d(in_channels, out_channels, kernel_size, groups = 1, stride = 1, padding = 0, dilation = 1, bias=True, prior_sigma_1 = 1, prior_sigma_2 = 0.002, prior_pi = 0.5, freeze = False) 110 | DESCRIPTION 111 | 112 | #### Parameters: 113 | * in_channels int -> incoming channels for the layer 114 | * out_channels int -> output channels for the layer 115 | * kernel_size tuple (int, int) -> size of the kernels for this convolution layer 116 | * groups int -> number of groups on which the convolutions will happend 117 | * padding int -> size of padding (0 if no padding) 118 | * dilation int -> dilation of the weights applied on the input tensor 119 | * bias bool -> whether the bias will exist (True) or set to zero (False) 120 | * prior_sigma_1 float -> prior sigma on the mixture prior distribution 1 121 | * prior_sigma_2 float -> prior sigma on the mixture prior distribution 2 122 | * prior_pi float -> pi on the scaled mixture prior 123 | * posterior_mu_init float -> posterior mean for the weight mu init 124 | * posterior_rho_init float -> posterior mean for the weight rho init 125 | * freeze bool -> wheter the model will start with frozen(deterministic) weights, or not 126 | * prior_dist -> torch.distributions.distribution.Distribution corresponding to a prior distribution different than a normal / scale mixture normal; if you pass that, the prior distribution will be that one and prior_sigma1 and prior_sigma2 and prior_pi can be dismissed. - Note that there is a torch issue that may output you logprob as NaN, so beware of the prior dist you are using. 127 | 128 | #### Methods: 129 | * forward(): 130 | 131 | Performs a feedforward Conv2d operation with sampled weights. If the model is frozen uses only the expected values. 132 | 133 | Returns torch.tensor 134 | 135 | Description 136 | ##### Parameters 137 | * x - torch.tensor corresponding to the datapoints tensor to be feedforwarded 138 | 139 | * forward_frozen(x): 140 | 141 | Performs a feedforward Conv2d operation using onle the mu tensor as weights. 142 | 143 | Returns torch.tensor 144 | 145 | Description 146 | ##### Parameters 147 | * x = torch.tensor corresponding to the datapoints tensor to be feedforwarded 148 | 149 | --- 150 | 151 | ## class BayesianConv3d 152 | ### blitz.modules.BayesianConv2d(in_channels, out_channels, kernel_size, groups = 1, stride = 1, padding = 0, dilation = 1, bias=True, prior_sigma_1 = 1, prior_sigma_2 = 0.002, prior_pi = 0.5, freeze = False) 153 | DESCRIPTION 154 | 155 | #### Parameters: 156 | * in_channels int -> incoming channels for the layer 157 | * out_channels int -> output channels for the layer 158 | * kernel_size tuple (int, int, int) -> size of the kernels for this convolution layer 159 | * groups int -> number of groups on which the convolutions will happend 160 | * padding int -> size of padding (0 if no padding) 161 | * dilation int -> dilation of the weights applied on the input tensor 162 | * bias bool -> whether the bias will exist (True) or set to zero (False) 163 | * prior_sigma_1 float -> prior sigma on the mixture prior distribution 1 164 | * prior_sigma_2 float -> prior sigma on the mixture prior distribution 2 165 | * prior_pi float -> pi on the scaled mixture prior 166 | * posterior_mu_init float -> posterior mean for the weight mu init 167 | * posterior_rho_init float -> posterior mean for the weight rho init 168 | * freeze bool -> wheter the model will start with frozen(deterministic) weights, or not 169 | * prior_dist -> torch.distributions.distribution.Distribution corresponding to a prior distribution different than a normal / scale mixture normal; if you pass that, the prior distribution will be that one and prior_sigma1 and prior_sigma2 and prior_pi can be dismissed. - Note that there is a torch issue that may output you logprob as NaN, so beware of the prior dist you are using. 170 | 171 | #### Methods: 172 | * forward(): 173 | 174 | Performs a feedforward Conv3d operation with sampled weights. If the model is frozen uses only the expected values. 175 | 176 | Returns torch.tensor 177 | 178 | Description 179 | ##### Parameters 180 | * x - torch.tensor corresponding to the datapoints tensor to be feedforwarded 181 | 182 | * forward_frozen(x): 183 | 184 | Performs a feedforward Conv2d operation using onle the mu tensor as weights. 185 | 186 | Returns torch.tensor 187 | 188 | Description 189 | ##### Parameters 190 | * x = torch.tensor corresponding to the datapoints tensor to be feedforwarded 191 | 192 | --- 193 | 194 | ## class BayesianLSTM 195 | ### blitz.modules.BayesianLSTM(in_features, out_features, bias=True, prior_sigma_1 = 1, prior_sigma_2 = 0.002, prior_pi = 0.5, freeze = False, peephole = False) 196 | 197 | Bayesian LSTM layer, implements the LSTM layer using the weight uncertainty tools proposed on Weight Uncertainity on Neural Networks (Bayes by Backprop paper). 198 | 199 | Creates weight samplers of the class TrainableRandomDistribution for the weights and biases to be used on its feedforward ops. 200 | 201 | Inherits from BayesianModule 202 | 203 | #### Parameters: 204 | * in_features int -> Number nodes of the information to be feedforwarded 205 | * out_features int -> Number of out nodes of the layer 206 | * bias bool -> wheter the model will have biases 207 | * prior_sigma_1 float -> sigma of one of the prior w distributions to mixture 208 | * prior_sigma_2 float -> sigma of one of the prior w distributions to mixture 209 | * prior_pi float -> factor to scale the gaussian mixture of the model prior distribution 210 | * posterior_mu_init float -> posterior mean for the weight mu init 211 | * posterior_rho_init float -> posterior mean for the weight rho init 212 | * freeze -> wheter the model is instaced as frozen (will use deterministic weights on the feedforward op) 213 | * peephole bool -> if the lstm shoudl use peephole connections rather than default ones 214 | * prior_dist -> torch.distributions.distribution.Distribution corresponding to a prior distribution different than a normal / scale mixture normal; if you pass that, the prior distribution will be that one and prior_sigma1 and prior_sigma2 and prior_pi can be dismissed. - Note that there is a torch issue that may output you logprob as NaN, so beware of the prior dist you are using. 215 | 216 | #### Methods: 217 | * forward(x, ): 218 | 219 | Performs a feedforward operation with sampled weights. If the model is frozen uses only the expected values. 220 | 221 | Returns tuple of format (torch.tensor, (torch.tensor, torch.tensor)), representing the output and hidden state of the LSTM layer 222 | 223 | Description 224 | ##### Parameters 225 | * x - torch.tensor corresponding to the datapoints tensor to be feedforwarded 226 | * hidden_states - None or tupl of the format (torch.tensor, torch.tensor), representing the hidden states of the network. Internally, if None, consider zeros of the proper format). 227 | 228 | * sample_weights(): 229 | 230 | Assings internally its weights to be used on feedforward operations by sampling it from its TrainableRandomDistribution 231 | 232 | * get_frozen_weights(): 233 | 234 | Assings internally for its weights deterministaclly the mean of its TrainableRandomDistribution sampler. 235 | 236 | --- 237 | 238 | ## class BayesianGRU 239 | ### blitz.modules.BayesianGRU(in_features, out_features, bias=True, prior_sigma_1 = 1, prior_sigma_2 = 0.002, prior_pi = 0.5, freeze = False) 240 | 241 | Bayesian GRU layer, implements the GRU layer using the weight uncertainty tools proposed on Weight Uncertainity on Neural Networks (Bayes by Backprop paper). 242 | 243 | Creates weight samplers of the class TrainableRandomDistribution for the weights and biases to be used on its feedforward ops. 244 | 245 | Inherits from BayesianModule 246 | 247 | #### Parameters: 248 | * in_features int -> Number nodes of the information to be feedforwarded 249 | * out_features int -> Number of out nodes of the layer 250 | * bias bool -> wheter the model will have biases 251 | * prior_sigma_1 float -> sigma of one of the prior w distributions to mixture 252 | * prior_sigma_2 float -> sigma of one of the prior w distributions to mixture 253 | * prior_pi float -> factor to scale the gaussian mixture of the model prior distribution 254 | * posterior_mu_init float -> posterior mean for the weight mu init 255 | * posterior_rho_init float -> posterior mean for the weight rho init 256 | * freeze -> wheter the model is instaced as frozen (will use deterministic weights on the feedforward op) 257 | * prior_dist -> torch.distributions.distribution.Distribution corresponding to a prior distribution different than a normal / scale mixture normal; if you pass that, the prior distribution will be that one and prior_sigma1 and prior_sigma2 and prior_pi can be dismissed. - Note that there is a torch issue that may output you logprob as NaN, so beware of the prior dist you are using. 258 | 259 | #### Methods: 260 | * forward(x, ): 261 | 262 | Performs a feedforward operation with sampled weights. If the model is frozen uses only the expected values. 263 | 264 | Returns tuple of format (torch.tensor, (torch.tensor, torch.tensor)), representing the output and hidden state of the GRU layer 265 | 266 | Description 267 | ##### Parameters 268 | * x - torch.tensor corresponding to the datapoints tensor to be feedforwarded 269 | * hidden_states - None or tupl of the format (torch.tensor, torch.tensor), representing the hidden states of the network. Internally, if None, consider zeros of the proper format). 270 | 271 | * sample_weights(): 272 | 273 | Assings internally its weights to be used on feedforward operations by sampling it from its TrainableRandomDistribution 274 | 275 | * get_frozen_weights(): 276 | 277 | Assings internally for its weights deterministaclly the mean of its TrainableRandomDistribution sampler. 278 | 279 | --- 280 | 281 | ## class BayesianEmbedding 282 | ### blitz.modules.BayesianEmbedding (num_embeddings, embedding_dim, padding_idx=None, max_norm=None, norm_type=2.0, scale_grad_by_freq=False, sparse=False, prior_sigma_1 = 1, prior_sigma_2 = 0.002, prior_pi = 0.5, freeze = False,) 283 | 284 | Bayesian Embedding layer, implements the Embedding layer using the weight uncertainty tools proposed on Weight Uncertainity on Neural Networks (Bayes by Backprop paper). 285 | 286 | Creates weight samplers of the class TrainableRandomDistribution for the weights and biases to be used on its feedforward ops. 287 | 288 | Inherits from BayesianModule 289 | 290 | #### Parameters: 291 | * num_embedding int -> Size of the vocabulary 292 | * embedding_dim int -> Dimension of the embedding 293 | * prior_sigma_1 float -> sigma of one of the prior w distributions to mixture 294 | * prior_sigma_2 float -> sigma of one of the prior w distributions to mixture 295 | * prior_pi float -> factor to scale the gaussian mixture of the model prior distribution 296 | * freeze -> wheter the model is instaced as frozen (will use deterministic weights on the feedforward op) 297 | * padding_idx int -> If given, pads the output with the embedding vector at padding_idx (initialized to zeros) whenever it encounters the index 298 | * max_norm float -> If given, each embedding vector with norm larger than max_norm is renormalized to have norm max_norm. 299 | * norm_type float -> The p of the p-norm to compute for the max_norm option. Default 2. 300 | * scale_grad_by_freq -> If given, this will scale gradients by the inverse of frequency of the words in the mini-batch. Default False. 301 | * sparse bool -> If True, gradient w.r.t. weight matrix will be a sparse tensor. See Notes for more details regarding sparse gradients. 302 | * posterior_mu_init float -> posterior mean for the weight mu init 303 | * posterior_rho_init float -> posterior mean for the weight rho init 304 | * prior_dist -> torch.distributions.distribution.Distribution corresponding to a prior distribution different than a normal / scale mixture normal; if you pass that, the prior distribution will be that one and prior_sigma1 and prior_sigma2 and prior_pi can be dismissed. - Note that there is a torch issue that may output you logprob as NaN, so beware of the prior dist you are using. 305 | 306 | 307 | 308 | #### Methods: 309 | * forward(x, ): 310 | 311 | Performs a embedding operation with sampled weights. If the model is frozen uses only the expected values. 312 | 313 | Returns tuple of format (torch.tensor, (torch.tensor, torch.tensor)), representing the output and hidden state of the GRU layer 314 | 315 | Description 316 | ##### Parameters 317 | * x - torch.tensor corresponding to the datapoints tensor to be feedforwarded 318 | * hidden_states - None or tupl of the format (torch.tensor, torch.tensor), representing the hidden states of the network. Internally, if None, consider zeros of the proper format). 319 | 320 | * sample_weights(): 321 | 322 | Assings internally its weights to be used on feedforward operations by sampling it from its TrainableRandomDistribution 323 | 324 | 325 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Blitz - Bayesian Layers in Torch Zoo 2 | 3 | [![Downloads](https://pepy.tech/badge/blitz-bayesian-pytorch)](https://pepy.tech/project/blitz-bayesian-pytorch) 4 | 5 | BLiTZ is a simple and extensible library to create Bayesian Neural Network Layers (based on whats proposed in [Weight Uncertainty in Neural Networks paper](https://arxiv.org/abs/1505.05424)) on PyTorch. By using BLiTZ layers and utils, you can add uncertanity and gather the complexity cost of your model in a simple way that does not affect the interaction between your layers, as if you were using standard PyTorch. 6 | 7 | By using our core weight sampler classes, you can extend and improve this library to add uncertanity to a bigger scope of layers as you will in a well-integrated to PyTorch way. Also pull requests are welcome. 8 | 9 | 10 | # Index 11 | * [Install](#Install) 12 | * [Documentation](#Documentation) 13 | * [A simple example for regression](#A-simple-example-for-regression) 14 | * [Importing the necessary modules](#Importing-the-necessary-modules) 15 | * [Loading and scaling data](#Loading-and-scaling-data) 16 | * [Creating our variational regressor class](#Creating-our-variational-regressor-class) 17 | * [Defining a confidence interval evaluating function](#Defining-a-confidence-interval-evaluating-function) 18 | * [Creating our regressor and loading data](#Creating-our-regressor-and-loading-data) 19 | * [Our main training and evaluating loop](#Our-main-training-and-evaluating-loop) 20 | * [Bayesian Deep Learning in a Nutshell](#Bayesian-Deep-Learning-in-a-Nutshell) 21 | * [First of all, a deterministic NN layer linear-transformation](#First-of-all,-a-deterministic-NN-layer-linear-transformation) 22 | * [The purpose of Bayesian Layers](#The-purpose-of-Bayesian-Layers) 23 | * [Weight sampling on Bayesian Layers](#Weight-sampling-on-Bayesian-Layers) 24 | * [It is possible to optimize our trainable weights](#It-is-possible-to-optimize-our-trainable-weights) 25 | * [It is also true that there is complexity cost function differentiable along its variables](#It-is-also-true-that-there-is-complexity-cost-function-differentiable-along-its-variables) 26 | * [To get the whole cost function at the nth sample](#To-get-the-whole-cost-function-at-the-nth-sample) 27 | * [Some notes and wrap up](#Some-notes-and-wrap-up) 28 | * [Citing](#Citing) 29 | * [References](#References) 30 | 31 | 32 | ## Install 33 | 34 | To install BLiTZ you can use pip command: 35 | 36 | ``` 37 | pip install blitz-bayesian-pytorch 38 | ``` 39 | Or, via conda: 40 | 41 | ``` 42 | conda install -c conda-forge blitz-bayesian-pytorch 43 | ``` 44 | 45 | You can also git-clone it and pip-install it locally: 46 | 47 | ``` 48 | conda create -n blitz python=3.9 49 | conda activate blitz 50 | git clone https://github.com/piEsposito/blitz-bayesian-deep-learning.git 51 | cd blitz-bayesian-deep-learning 52 | pip install . 53 | ``` 54 | 55 | ## Documentation 56 | 57 | Documentation for our layers, weight (and prior distribution) sampler and utils: 58 | * [Bayesian Layers](doc/layers.md) 59 | * [Weight and prior distribution samplers](doc/samplers.md) 60 | * [Utils (for easy integration with PyTorch)](doc/utils.md) 61 | * [Losses](doc/losses.md) 62 | 63 | ## A simple example for regression 64 | 65 | (You can see it for your self by running [this example](blitz/examples/bayesian_regression_boston.py) on your machine). 66 | 67 | We will now see how can Bayesian Deep Learning be used for regression in order to gather confidence interval over our datapoint rather than a pontual continuous value prediction. Gathering a confidence interval for your prediction may be even a more useful information than a low-error estimation. 68 | 69 | I sustain my argumentation on the fact that, with good/high prob a confidence interval, you can make a more reliable decision than with a very proximal estimation on some contexts: if you are trying to get profit from a trading operation, for example, having a good confidence interval may lead you to know if, at least, the value on which the operation wil procees will be lower (or higher) than some determinate X. 70 | 71 | Knowing if a value will be, surely (or with good probability) on a determinate interval can help people on sensible decision more than a very proximal estimation that, if lower or higher than some limit value, may cause loss on a transaction. The point is that, sometimes, knowing if there will be profit may be more useful than measuring it. 72 | 73 | In order to demonstrate that, we will create a Bayesian Neural Network Regressor for the Boston-house-data toy dataset, trying to create confidence interval (CI) for the houses of which the price we are trying to predict. We will perform some scaling and the CI will be about 75%. It will be interesting to see that about 90% of the CIs predicted are lower than the high limit OR (inclusive) higher than the lower one. 74 | 75 | ## Importing the necessary modules 76 | Despite from the known modules, we will bring from BLiTZ athe `variational_estimator`decorator, which helps us to handle the BayesianLinear layers on the module keeping it fully integrated with the rest of Torch, and, of course, `BayesianLinear`, which is our layer that features weight uncertanity. 77 | 78 | ```python 79 | import torch 80 | import torch.nn as nn 81 | import torch.nn.functional as F 82 | import torch.optim as optim 83 | import numpy as np 84 | 85 | from blitz.modules import BayesianLinear 86 | from blitz.utils import variational_estimator 87 | 88 | from sklearn.datasets import load_boston 89 | from sklearn.preprocessing import StandardScaler 90 | from sklearn.model_selection import train_test_split 91 | ``` 92 | 93 | ## Loading and scaling data 94 | 95 | Nothing new under the sun here, we are importing and standard-scaling the data to help with the training. 96 | 97 | ```python 98 | X, y = load_boston(return_X_y=True) 99 | X = StandardScaler().fit_transform(X) 100 | y = StandardScaler().fit_transform(np.expand_dims(y, -1)) 101 | 102 | X_train, X_test, y_train, y_test = train_test_split(X, 103 | y, 104 | test_size=.25, 105 | random_state=42) 106 | 107 | 108 | X_train, y_train = torch.tensor(X_train).float(), torch.tensor(y_train).float() 109 | X_test, y_test = torch.tensor(X_test).float(), torch.tensor(y_test).float() 110 | ``` 111 | 112 | # Creating our variational regressor class 113 | 114 | We can create our class with inhreiting from nn.Module, as we would do with any Torch network. Our decorator introduces the methods to handle the bayesian features, as calculating the complexity cost of the Bayesian Layers and doing many feedforwards (sampling different weights on each one) in order to sample our loss. 115 | 116 | ```python 117 | @variational_estimator 118 | class BayesianRegressor(nn.Module): 119 | def __init__(self, input_dim, output_dim): 120 | super().__init__() 121 | #self.linear = nn.Linear(input_dim, output_dim) 122 | self.blinear1 = BayesianLinear(input_dim, 512) 123 | self.blinear2 = BayesianLinear(512, output_dim) 124 | 125 | def forward(self, x): 126 | x_ = self.blinear1(x) 127 | x_ = F.relu(x_) 128 | return self.blinear2(x_) 129 | ``` 130 | 131 | # Defining a confidence interval evaluating function 132 | 133 | This function does create a confidence interval for each prediction on the batch on which we are trying to sample the label value. We then can measure the accuracy of our predictions by seeking how much of the prediciton distributions did actually include the correct label for the datapoint. 134 | 135 | 136 | ```python 137 | def evaluate_regression(regressor, 138 | X, 139 | y, 140 | samples = 100, 141 | std_multiplier = 2): 142 | preds = [regressor(X) for i in range(samples)] 143 | preds = torch.stack(preds) 144 | means = preds.mean(axis=0) 145 | stds = preds.std(axis=0) 146 | ci_upper = means + (std_multiplier * stds) 147 | ci_lower = means - (std_multiplier * stds) 148 | ic_acc = (ci_lower <= y) * (ci_upper >= y) 149 | ic_acc = ic_acc.float().mean() 150 | return ic_acc, (ci_upper >= y).float().mean(), (ci_lower <= y).float().mean() 151 | ``` 152 | 153 | # Creating our regressor and loading data 154 | 155 | Notice here that we create our `BayesianRegressor` as we would do with other neural networks. 156 | 157 | ```python 158 | regressor = BayesianRegressor(13, 1) 159 | optimizer = optim.Adam(regressor.parameters(), lr=0.01) 160 | criterion = torch.nn.MSELoss() 161 | 162 | ds_train = torch.utils.data.TensorDataset(X_train, y_train) 163 | dataloader_train = torch.utils.data.DataLoader(ds_train, batch_size=16, shuffle=True) 164 | 165 | ds_test = torch.utils.data.TensorDataset(X_test, y_test) 166 | dataloader_test = torch.utils.data.DataLoader(ds_test, batch_size=16, shuffle=True) 167 | ``` 168 | 169 | ## Our main training and evaluating loop 170 | 171 | We do a training loop that only differs from a common torch training by having its loss sampled by its sample_elbo method. All the other stuff can be done normally, as our purpose with BLiTZ is to ease your life on iterating on your data with different Bayesian NNs without trouble. 172 | 173 | Here is our very simple training loop: 174 | 175 | ```python 176 | iteration = 0 177 | for epoch in range(100): 178 | for i, (datapoints, labels) in enumerate(dataloader_train): 179 | optimizer.zero_grad() 180 | 181 | loss = regressor.sample_elbo(inputs=datapoints, 182 | labels=labels, 183 | criterion=criterion, 184 | sample_nbr=3) 185 | loss.backward() 186 | optimizer.step() 187 | 188 | iteration += 1 189 | if iteration%100==0: 190 | ic_acc, under_ci_upper, over_ci_lower = evaluate_regression(regressor, 191 | X_test, 192 | y_test, 193 | samples=25, 194 | std_multiplier=3) 195 | 196 | print("CI acc: {:.2f}, CI upper acc: {:.2f}, CI lower acc: {:.2f}".format(ic_acc, under_ci_upper, over_ci_lower)) 197 | print("Loss: {:.4f}".format(loss)) 198 | ``` 199 | 200 | ## Bayesian Deep Learning in a Nutshell 201 | A very fast explanation of how is uncertainity introduced in Bayesian Neural Networks and how we model its loss in order to objectively improve the confidence over its prediction and reduce the variance without dropout. 202 | 203 | ## First of all, a deterministic NN layer linear transformation 204 | 205 | As we know, on deterministic (non bayesian) neural network layers, the trainable parameters correspond directly to the weights used on its linear transformation of the previous one (or the input, if it is the case). It corresponds to the following equation: 206 | 207 | 208 | ![equation](https://latex.codecogs.com/gif.latex?a^{(i+1)}&space;=&space;W^{(i+1)}\cdot&space;z^{(i)}&space;+&space;b^{(i+1)}) 209 | 210 | *(Z correspond to the activated-output of the layer i)* 211 | 212 | ## The purpose of Bayesian Layers 213 | 214 | Bayesian layers seek to introduce uncertainity on its weights by sampling them from a distribution parametrized by trainable variables on each feedforward operation. 215 | 216 | This allows we not just to optimize the performance metrics of the model, but also gather the uncertainity of the network predictions over a specific datapoint (by sampling it much times and measuring the dispersion) and aimingly reduce as much as possible the variance of the network over the prediction, making possible to know how much of incertainity we still have over the label if we try to model it in function of our specific datapoint. 217 | 218 | ## Weight sampling on Bayesian Layers 219 | To do so, on each feedforward operation we sample the parameters of the linear transformation with the following equations (where **ρ** parametrizes the standard deviation and **μ** parametrizes the mean for the samples linear transformation parameters) : 220 | 221 | For the weights: 222 | 223 | ![equation](https://latex.codecogs.com/gif.latex?W^{(i)}_{(n)}&space;=&space;\mathcal{N}(0,1)&space;*&space;log(1&space;+&space;\rho^{(i)}&space;)&space;+&space;\mu^{(i)}) 224 | 225 | *Where the sampled W corresponds to the weights used on the linear transformation for the ith layer on the nth sample.* 226 | 227 | For the biases: 228 | 229 | ![equation](https://latex.codecogs.com/gif.latex?b^{(i)}_{(n)}&space;=&space;\mathcal{N}(0,1)&space;*&space;log(1&space;+&space;\rho^{(i)}&space;)&space;+&space;\mu^{(i)}) 230 | 231 | *Where the sampled b corresponds to the biases used on the linear transformation for the ith layer on the nth sample.* 232 | 233 | ## It is possible to optimize our trainable weights 234 | 235 | Even tough we have a random multiplier for our weights and biases, it is possible to optimize them by, given some differentiable function of the weights sampled and trainable parameters (in our case, the loss), summing the derivative of the function relative to both of them: 236 | 237 | 1. Let ![equation](https://latex.codecogs.com/gif.latex?\epsilon&space;=&space;\mathcal{N}(0,1)) 238 | 2. Let ![equation](https://latex.codecogs.com/gif.latex?\theta&space;=&space;(\rho,&space;\mu)) 239 | 3. Let ![equation](https://latex.codecogs.com/gif.latex?w&space;=&space;\mu&space;+&space;\log({1&space;+&space;e^{\rho}})&space;*&space;\epsilon) 240 | 4. Let ![equation](https://latex.codecogs.com/gif.latex?f(w,&space;\theta)) be differentiable relative to its variables 241 | 242 | Therefore: 243 | 244 | 5. ![equation](https://latex.codecogs.com/gif.latex?\Delta_{\mu}&space;=&space;\frac{\delta&space;f(w,&space;\theta)}{\delta&space;w}&space;+&space;\frac{\delta&space;f(w,&space;\theta)}{\delta&space;\mu}) 245 | 246 | and 247 | 248 | 249 | 6. ![equation](https://latex.codecogs.com/gif.latex?\Delta_{\rho}&space;=&space;\frac{\delta&space;f(w,&space;\theta)}{\delta&space;w}&space;\frac{\epsilon}{1&space;+&space;e^\rho&space;}&space;+&space;\frac{\delta&space;f(w,&space;\theta)}{\delta&space;\rho}) 250 | 251 | ## It is also true that there is complexity cost function differentiable along its variables 252 | 253 | It is known that the crossentropy loss (and MSE) are differentiable. Therefore if we prove that there is a complexity-cost function that is differentiable, we can leave it to our framework take the derivatives and compute the gradients on the optimization step. 254 | 255 | **The complexity cost is calculated, on the feedforward operation, by each of the Bayesian Layers, (with the layers pre-defined-simpler apriori distribution and its empirical distribution). The sum of the complexity cost of each layer is summed to the loss.** 256 | 257 | As proposed in [Weight Uncertainty in Neural Networks paper](https://arxiv.org/abs/1505.05424), we can gather the complexity cost of a distribution by taking the [Kullback-Leibler Divergence](https://jhui.github.io/2017/01/05/Deep-learning-Information-theory/) from it to a much simpler distribution, and by making some approximation, we will can differentiate this function relative to its variables (the distributions): 258 | 259 | 1. Let ![equation](https://latex.codecogs.com/gif.latex?{P}(w)) be a low-entropy distribution pdf set by hand, which will be assumed as an "a priori" distribution for the weights 260 | 261 | 2. Let ![equation](https://latex.codecogs.com/gif.latex?{Q}(w&space;|&space;\theta)) be the a posteriori empirical distribution pdf for our sampled weights, given its parameters. 262 | 263 | 264 | 265 | 266 | Therefore, for each scalar on the W sampled matrix: 267 | 268 | 269 | 270 | 271 | 3. ![equation](https://latex.codecogs.com/gif.latex?{D}_{KL}(&space;{Q}(w&space;|&space;\theta)&space;\lVert&space;{P}(w)&space;)&space;=&space;\lim_{n\to\infty}1/n\sum_{i=0}^{n}&space;{Q}(w^{(i)}&space;|&space;\theta)*&space;(\log{{Q}(w^{(i)}&space;|&space;\theta)}&space;-&space;\log{{P}(w^{(i)})}&space;)) 272 | 273 | 274 | By assuming a very large n, we could approximate: 275 | 276 | 4. ![equation](https://latex.codecogs.com/gif.latex?{D}_{KL}(&space;{Q}(w&space;|&space;\theta)&space;\lVert&space;{P}(w)&space;)&space;=&space;1/n\sum_{i=0}^{n}&space;{Q}(w^{(i)}&space;|&space;\theta)*&space;(\log{{Q}(w^{(i)}&space;|&space;\theta)}&space;-&space;\log{{P}(w^{(i)})}&space;)) 277 | 278 | 279 | and therefore: 280 | 281 | 282 | 5. ![equation](https://latex.codecogs.com/gif.latex?{D}_{KL}(&space;{Q}(w&space;|&space;\theta)&space;\lVert&space;{P}(w)&space;)&space;=&space;\mu_Q&space;*\sum_{i=0}^{n}&space;(\log{{Q}(w^{(i)}&space;|&space;\theta)}&space;-&space;\log{{P}(w^{(i)})}&space;)) 283 | 284 | 285 | As the expected (mean) of the Q distribution ends up by just scaling the values, we can take it out of the equation (as there will be no framework-tracing). Have a complexity cost of the nth sample as: 286 | 287 | 6. ![equation](https://latex.codecogs.com/gif.latex?{C^{(n)}&space;(w^{(n)},&space;\theta)&space;}&space;=&space;(\log{{Q}(w^{(n)}&space;|&space;\theta)}&space;-&space;\log{{P}(w^{(n)})}&space;)) 288 | 289 | Which is differentiable relative to all of its parameters. 290 | 291 | ## To get the whole cost function at the nth sample: 292 | 293 | 1. Let a performance (fit to data) function be: ![equation](https://latex.codecogs.com/gif.latex?{P^{(n)}&space;(w^{(n)},&space;\theta)}) 294 | 295 | 296 | Therefore the whole cost function on the nth sample of weights will be: 297 | 298 | 2. ![equation](https://latex.codecogs.com/gif.latex?{L^{(n)}&space;(w^{(n)},&space;\theta)&space;}&space;=&space;{C^{(n)}&space;(w^{(n)},&space;\theta)&space;}&space;+&space;{P^{(n)}&space;(w^{(n)},&space;\theta)&space;}) 299 | 300 | We can estimate the true full Cost function by Monte Carlo sampling it (feedforwarding the netwok X times and taking the mean over full loss) and then backpropagate using our estimated value. It works for a low number of experiments per backprop and even for unitary experiments. 301 | 302 | ## Some notes and wrap up 303 | We came to the end of a Bayesian Deep Learning in a Nutshell tutorial. By knowing what is being done here, you can implement your bnn model as you wish. 304 | 305 | Maybe you can optimize by doing one optimize step per sample, or by using this Monte-Carlo-ish method to gather the loss some times, take its mean and then optimizer. Your move. 306 | 307 | FYI: **Our Bayesian Layers and utils help to calculate the complexity cost along the layers on each feedforward operation, so don't mind it to much.** 308 | 309 | ## References: 310 | * [Charles Blundell, Julien Cornebise, Koray Kavukcuoglu, and Daan Wierstra. Weight uncertainty in neural networks. arXiv preprint arXiv:1505.05424, 2015.](https://arxiv.org/abs/1505.05424) 311 | 312 | 313 | ## Citing 314 | 315 | If you use `BLiTZ` in your research, you can cite it as follows: 316 | 317 | ```bibtex 318 | @misc{esposito2020blitzbdl, 319 | author = {Piero Esposito}, 320 | title = {BLiTZ - Bayesian Layers in Torch Zoo (a Bayesian Deep Learing library for Torch)}, 321 | year = {2020}, 322 | publisher = {GitHub}, 323 | journal = {GitHub repository}, 324 | howpublished = {\url{https://github.com/piEsposito/blitz-bayesian-deep-learning/}}, 325 | } 326 | ``` 327 | 328 | ###### Made by Pi Esposito 329 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------