-
Notifications
You must be signed in to change notification settings - Fork 78
/
Copy pathdnn_to_bnn.py
165 lines (151 loc) · 6.2 KB
/
dnn_to_bnn.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
# Copyright (C) 2024 Intel Labs
#
# BSD-3-Clause License
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
# OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
# OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Functions related to DNN to BNN model conversion.
#
# @authors: Mahesh Subedar
#
# ===============================================================================================
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import bayesian_torch.layers as bayesian_layers
from bayesian_torch.utils.util import get_rho
# --------------------------------------------------------------------------------
# Parameters used to define BNN layyers.
# bnn_prior_parameters = {
# "prior_mu": 0.0,
# "prior_sigma": 1.0,
# "posterior_mu_init": 0.0,
# "posterior_rho_init": -4.0,
# "type": "Reparameterization", # Flipout or Reparameterization
# }
def bnn_linear_layer(params, d):
layer_type = d.__class__.__name__ + params["type"]
layer_fn = getattr(bayesian_layers, layer_type) # Get BNN layer
bnn_layer = layer_fn(
in_features=d.in_features,
out_features=d.out_features,
prior_mean=params["prior_mu"],
prior_variance=params["prior_sigma"],
posterior_mu_init=params["posterior_mu_init"],
posterior_rho_init=params["posterior_rho_init"],
bias=d.bias is not None,
)
# if MOPED is enabled initialize mu and sigma
if params["moped_enable"]:
delta = params["moped_delta"]
bnn_layer.mu_weight.data.copy_(d.weight.data)
bnn_layer.rho_weight.data.copy_(get_rho(d.weight.data, delta))
if bnn_layer.mu_bias is not None:
bnn_layer.mu_bias.data.copy_(d.bias.data)
bnn_layer.rho_bias.data.copy_(get_rho(d.bias.data, delta))
bnn_layer.dnn_to_bnn_flag = True
return bnn_layer
def bnn_conv_layer(params, d):
layer_type = d.__class__.__name__ + params["type"]
layer_fn = getattr(bayesian_layers, layer_type) # Get BNN layer
bnn_layer = layer_fn(
in_channels=d.in_channels,
out_channels=d.out_channels,
kernel_size=d.kernel_size,
stride=d.stride,
padding=d.padding,
dilation=d.dilation,
groups=d.groups,
prior_mean=params["prior_mu"],
prior_variance=params["prior_sigma"],
posterior_mu_init=params["posterior_mu_init"],
posterior_rho_init=params["posterior_rho_init"],
bias=d.bias is not None,
)
# if MOPED is enabled, initialize mu and sigma
if params["moped_enable"]:
delta = params["moped_delta"]
bnn_layer.mu_kernel.data.copy_(d.weight.data)
bnn_layer.rho_kernel.data.copy_(get_rho(d.weight.data, delta))
if bnn_layer.mu_bias is not None:
bnn_layer.mu_bias.data.copy_(d.bias.data)
bnn_layer.rho_bias.data.copy_(get_rho(d.bias.data, delta))
bnn_layer.dnn_to_bnn_flag = True
return bnn_layer
def bnn_lstm_layer(params, d):
layer_type = d.__class__.__name__ + params["type"]
layer_fn = getattr(bayesian_layers, layer_type) # Get BNN layer
bnn_layer = layer_fn(
in_features=d.input_size,
out_features=d.hidden_size,
prior_mean=params["prior_mu"],
prior_variance=params["prior_sigma"],
posterior_mu_init=params["posterior_mu_init"],
posterior_rho_init=params["posterior_rho_init"],
bias=d.bias is not None,
)
# if MOPED is enabled initialize mu and sigma
if params["moped_enable"]:
print("WARNING: MOPED method is not supported for LSTM layers!!!")
bnn_layer.dnn_to_bnn_flag = True
return bnn_layer
# replaces linear and conv layers
# bnn_prior_parameters - check the template at the top.
def dnn_to_bnn(m, bnn_prior_parameters):
for name, value in list(m._modules.items()):
if m._modules[name]._modules:
dnn_to_bnn(m._modules[name], bnn_prior_parameters)
elif "Conv" in m._modules[name].__class__.__name__:
setattr(
m,
name,
bnn_conv_layer(
bnn_prior_parameters,
m._modules[name]))
elif "Linear" in m._modules[name].__class__.__name__:
setattr(
m,
name,
bnn_linear_layer(
bnn_prior_parameters,
m._modules[name]))
elif "LSTM" in m._modules[name].__class__.__name__:
setattr(
m,
name,
bnn_lstm_layer(
bnn_prior_parameters,
m._modules[name]))
else:
pass
return
def get_kl_loss(m):
kl_loss = None
for layer in m.modules():
if hasattr(layer, "kl_loss"):
if kl_loss is None:
kl_loss = layer.kl_loss()
else:
kl_loss += layer.kl_loss()
return kl_loss