-
Notifications
You must be signed in to change notification settings - Fork 3
/
hyperlayers.py
executable file
·186 lines (148 loc) · 7.43 KB
/
hyperlayers.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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
import numpy as np
'''Pytorch implementations of hyper-network modules.'''
from torch import nn
import torch
from torchmeta.modules import (MetaModule, MetaSequential)
import custom_layers
from collections import OrderedDict
class LowRankHyperNetwork(nn.Module):
def __init__(self, hyper_in_features, hyper_hidden_layers, hyper_hidden_features, hypo_module, linear=False,
rank=10, nonlinearity='relu'):
'''
Args:
hyper_in_features: In features of hypernetwork
hyper_hidden_layers: Number of hidden layers in hypernetwork
hyper_hidden_features: Number of hidden units in hypernetwork
hypo_module: MetaModule. The module whose parameters are predicted.
'''
super().__init__()
self.hypo_parameters = dict(hypo_module.meta_named_parameters())
# self.embedding_net = modules.FCBlock(in_features=hyper_in_features, out_features=hyper_hidden_features,
# num_hidden_layers=1, hidden_ch=hyper_hidden_features)
self.representation_dim = 0
self.rank = rank
self.names = []
self.nets = nn.ModuleList()
self.param_shapes = []
for name, param in self.hypo_parameters.items():
self.names.append(name)
self.param_shapes.append(param.size())
out_features = int(torch.prod(torch.tensor(param.size()))) if 'bias' in name else param.shape[0]*rank + param.shape[1]*rank
self.representation_dim += out_features
hn = custom_layers.FCBlock(in_features=hyper_in_features, out_features=out_features,
num_hidden_layers=hyper_hidden_layers, hidden_ch=hyper_hidden_features,
outermost_linear=True, norm=None, nonlinearity=nonlinearity)
if 'bias' in name:
hn.net[-1].bias.data = torch.zeros_like(hn.net[-1].bias.data)
else:
hn.net[-1].bias.data = torch.ones_like(hn.net[-1].bias.data) / np.sqrt(self.rank)
hn.net[-1].weight.data *= 1e-1
self.nets.append(hn)
def forward(self, z):
'''
Args:
z: Embedding. Input to hypernetwork. Could be output of "Autodecoder" (see above)
Returns:
params: OrderedDict. Can be directly passed as the "params" parameter of a MetaModule.
'''
# embedding = self.embedding_net(z)
params = OrderedDict()
representation = []
for name, net, param_shape in zip(self.names, self.nets, self.param_shapes):
low_rank_params = net(z)
representation.append(low_rank_params)
if 'bias' in name:
batch_param_shape = (-1,) + param_shape
params[name] = self.hypo_parameters[name] + low_rank_params.reshape(batch_param_shape)
else:
a = low_rank_params[:, :self.rank*param_shape[0]].view(-1, param_shape[0], self.rank)
b = low_rank_params[:, self.rank*param_shape[0]:].view(-1, self.rank, param_shape[1])
low_rank_w = a.matmul(b)
params[name] = self.hypo_parameters[name] * low_rank_w
# params[name] = self.hypo_parameters[name] * torch.sigmoid(low_rank_w)
return params
class HyperNetwork(nn.Module):
def __init__(self, hyper_in_features, hyper_hidden_layers, hyper_hidden_features, hypo_module,siren=False):
'''
Args:
hyper_in_features: In features of hypernetwork
hyper_hidden_layers: Number of hidden layers in hypernetwork
hyper_hidden_features: Number of hidden units in hypernetwork
hypo_module: MetaModule. The module whose parameters are predicted.
'''
super().__init__()
hypo_parameters = hypo_module.meta_named_parameters()
self.names = []
self.nets = nn.ModuleList()
self.param_shapes = []
for name, param in hypo_parameters:
self.names.append(name)
self.param_shapes.append(param.size())
hn = custom_layers.FCBlock(in_features=hyper_in_features, out_features=int(torch.prod(torch.tensor(param.size()))),
num_hidden_layers=hyper_hidden_layers, hidden_ch=hyper_hidden_features,
outermost_linear=True, norm='layernorm')
if 'weight' in name:
hn.net[-1].apply(lambda m: hyper_weight_init(m, param.size()[-1], siren=siren))
elif 'bias' in name:
hn.net[-1].apply(lambda m: hyper_bias_init(m, siren=siren))
self.nets.append(hn)
def forward(self, z):
'''
Args:
z: Embedding. Input to hypernetwork. Could be output of "Autodecoder" (see above)
Returns:
params: OrderedDict. Can be directly passed as the "params" parameter of a MetaModule.
'''
params = OrderedDict()
for name, net, param_shape in zip(self.names, self.nets, self.param_shapes):
batch_param_shape = (-1,) + param_shape
params[name] = net(z).reshape(batch_param_shape)
return params
class FILMNetwork(nn.Module):
def __init__(self, hypo_module, latent_dim, num_hidden=3):
'''
Args:
hyper_in_features: In features of hypernetwork
hyper_hidden_layers: Number of hidden layers in hypernetwork
hyper_hidden_features: Number of hidden units in hypernetwork
hypo_module: MetaModule. The module whose parameters are predicted.
'''
super().__init__()
hypo_parameters = hypo_module.meta_named_parameters()
self.names = []
self.nets = nn.ModuleList()
self.param_shapes = []
for name, param in hypo_parameters:
self.names.append(name)
self.param_shapes.append(param.size())
hn = custom_layers.FCBlock(in_features=latent_dim, out_features=int(2*torch.tensor(param.shape[0])),
num_hidden_layers=num_hidden, hidden_ch=latent_dim, outermost_linear=True,
nonlinearity='relu')
# hn.net[-1].apply(lambda m: hyper_weight_init(m, param.size()[-1]))
self.nets.append(hn)
def forward(self, z):
params = []
for name, net, param_shape in zip(self.names, self.nets, self.param_shapes):
net_out = net(z)
layer_params = {}
layer_params['gamma'] = net_out[:, :param_shape[0]].unsqueeze(1) + 1
layer_params['beta'] = net_out[:, param_shape[0]:].unsqueeze(1)
params.append(layer_params)
return params
############################
# Initialization scheme
def hyper_weight_init(m, in_features_main_net, siren=False):
if hasattr(m, 'weight'):
nn.init.kaiming_normal_(m.weight, a=0.0, nonlinearity='relu', mode='fan_in')
m.weight.data = m.weight.data / 1e1
if hasattr(m, 'bias') and siren:
with torch.no_grad():
m.bias.uniform_(-1/in_features_main_net, 1/in_features_main_net)
def hyper_bias_init(m, siren=False):
if hasattr(m, 'weight'):
nn.init.kaiming_normal_(m.weight, a=0.0, nonlinearity='relu', mode='fan_in')
m.weight.data = m.weight.data / 1.e1
if hasattr(m, 'bias') and siren:
fan_in, _ = nn.init._calculate_fan_in_and_fan_out(m.weight)
with torch.no_grad():
m.bias.uniform_(-1/fan_in, 1/fan_in)