-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtorch.py
202 lines (155 loc) · 7.16 KB
/
torch.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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import torch
from torch import nn
class LSH(nn.Module):
def __init__(self, **kwargs):
super().__init__()
self.batch : bool = kwargs.get("batch", False)
self.name : str = kwargs.get("name","LSH")
self.input_length : int = kwargs.get("input_length",0)
self.output_length : int = kwargs.get("output_length",1)
self.hashtype : str = kwargs.get("hashtype","real")
self.width : int = kwargs.get("width",None)
if self.hashtype == "binary":
self.nbins = 2
if self.hashtype == "integer":
if self.width is None:
raise Exception("The parameter width must be informed!")
self.b = np.random.randint(0, self.width, 1)
def hash(self, input : np.array, **kwargs):
return self.forward(torch.from_numpy(input), **kwargs)
class SignedRandomProjectionLSH(LSH):
def __init__(self, **kwargs):
super(SignedRandomProjectionLSH, self).__init__(**kwargs)
scale = kwargs.get("scale", 1.0)
dist = kwargs.get('dist','unif')
if dist == 'normal':
self.weights = nn.Parameter(torch.randn(self.input_length) * scale, requires_grad=False)
elif dist == 'unif':
self.weights = nn.Parameter((torch.rand(self.input_length) * (scale * 2)) - scale, requires_grad=False)
def forward(self, input):
return input @ self.weights
class MultipleLSH(LSH):
def __init__(self, **kwargs):
super(MultipleLSH, self).__init__(**kwargs)
# It is important to keep the number of components and the output length as separated attributes
self.output_length = self.num_components = kwargs.get("num_components", 2)
self.scale = kwargs.get("scale", 1.0)
self.dist = kwargs.get('dist','unif')
if self.dist == 'normal':
self.weights = nn.Parameter(torch.randn(self.num_components, self.input_length) * self.scale, requires_grad=False)
elif self.dist == 'unif':
self.weights = nn.Parameter((torch.rand(self.num_components, self.input_length) * (self.scale * 2)) - self.scale, requires_grad=False)
def forward(self, input):
ret = torch.zeros((len(input), self.num_components))
for k in range(self.num_components):
ret[:,k] = input @ self.weights[k,:]
return ret
class MultipleRandomSampledLSH(LSH):
def __init__(self, **kwargs):
super(MultipleRandomSampledLSH, self).__init__(**kwargs)
self.output_length = self.num_components = kwargs.get("num_components", 2)
self.sample_size : int = kwargs.get("sample_size", self.input_length // 2) # Sample must be lower than length
self.scale = kwargs.get("scale", 1.0)
self.dist = kwargs.get('dist','unif')
if self.dist == 'normal':
self.weights = nn.Parameter(torch.randn(self.num_components, self.sample_size) * self.scale, requires_grad=False)
elif self.dist == 'unif':
self.weights = nn.Parameter((torch.rand(self.num_components, self.sample_size) * (self.scale * 2)) - self.scale, requires_grad=False)
self.sample_indexes = []
for k in range(self.output_length):
self.sample_indexes.append( [int(k) for k in np.random.choice(self.input_length, self.sample_size, replace = False)] )
def forward(self, input):
ret = torch.zeros((len(input), self.num_components))
for k in range(self.num_components):
i = input[:,self.sample_indexes[k]]
ret[:,k] = i @ self.weights[k,:]
return ret
class EnsembleLSH(MultipleLSH):
def __init__(self, **kwargs):
super(EnsembleLSH, self).__init__(**kwargs)
self.output_length = 1
self.aggregation : str = kwargs.get("aggregation", "srp")
self.aggregation_weights = kwargs.get("aggregation_weights",None)
if not self.aggregation_weights is None:
self.aggregation = "custom"
if self.aggregation == "custom":
self.aggregation_fn = lambda x : x @ self.aggregation_weights
elif self.aggregation == "srp":
self.scale = kwargs.get("scale", 1.0)
self.dist = kwargs.get('dist','unif')
if self.dist == 'normal':
self.aggregation_weights = nn.Parameter(torch.randn(self.num_components) * self.scale, requires_grad=False)
elif self.dist == 'unif':
self.aggregation_weights = nn.Parameter((torch.rand(self.num_components) * (self.scale * 2)) - self.scale, requires_grad=False)
self.aggregation_fn = lambda x : x @ self.aggregation_weights
elif self.aggregation == "mean":
self.aggregation_fn = lambda x : torch.mean(x, dim=1)
elif self.aggregation == "max":
self.aggregation_fn = lambda x : torch.max(x, dim=1)
elif self.aggregation == "min":
self.aggregation_fn = lambda x : torch.min(x, dim=1)
else:
raise Exception("Unknown aggregation")
def forward(self, input):
hashes = super(EnsembleLSH, self).forward(input)
return self.aggregation_fn(hashes)
class RandomSampleEnsembleLSH(MultipleRandomSampledLSH):
def __init__(self, **kwargs):
super(RandomSampleEnsembleLSH, self).__init__(**kwargs)
self.output_length = 1
self.aggregation : str = kwargs.get("aggregation", "srp")
self.aggregation_weights = kwargs.get("aggregation_weights",None)
if not self.aggregation_weights is None:
self.aggregation = "custom"
if self.aggregation == "custom":
self.aggregation_fn = lambda x : x @ self.aggregation_weights
elif self.aggregation == "srp":
self.scale = kwargs.get("scale", 1.0)
self.dist = kwargs.get('dist','unif')
if self.dist == 'normal':
self.aggregation_weights = nn.Parameter(torch.randn(self.num_components) * self.scale, requires_grad=False)
elif self.dist == 'unif':
self.aggregation_weights = nn.Parameter((torch.rand(self.num_components) * (self.scale * 2)) - self.scale, requires_grad=False)
self.aggregation_fn = lambda x : x @ self.aggregation_weights
elif self.aggregation == "mean":
self.aggregation_fn = lambda x : torch.mean(x, dim=1)
elif self.aggregation == "max":
self.aggregation_fn = lambda x : torch.max(x, dim=1)
elif self.aggregation == "min":
self.aggregation_fn = lambda x : torch.min(x, dim=1)
else:
raise Exception("Unknown aggregation")
def forward(self, input : np.array, **kwargs):
hashes = super(RandomSampleEnsembleLSH, self).forward(input)
return self.aggregation_fn(hashes)
class SequentialLSH(LSH):
def __init__(self, *args : LSH):
super().__init__()
for idx, module in enumerate(args):
self.add_module(str(idx), module)
if idx == 0:
self.input_length = module.input_length
self.output_length = module.output_length
def forward(self, input):
old = input
for key, layer in self._modules.items():
ct = int(key)
if ct == 0:
new = layer.forward(old)
else:
n = len(old)
if self._modules[str(ct-1)].output_length != layer.input_length:
_nn = n // layer.input_length
new = torch.zeros((_nn, layer.output_length))
for k in range(1, _nn):
ix = k * layer.input_length
new[k, :] = layer.forward(old[ix - layer.input_length : ix])
else:
new = layer.forward(old)
if layer.output_length == 1:
new = new.flatten()
old = new
return old