-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathesc.py
215 lines (191 loc) · 8.36 KB
/
esc.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
203
204
205
206
207
208
209
210
211
212
213
214
215
import math
import torch
import numpy
from sc import Field, DoubleField, FloatField
from utils import biggest_divisor_smaller_than
class EfficientStructuralCoding:
def __init__(self, n, k, data: torch.Tensor, dim=0, field: Field = None, use_woodbury=True) -> None:
self.n = n
self.k = k
self.dim = dim
self.use_woodbury = use_woodbury
assert dim == 0
if field is None:
if torch.get_default_dtype() == torch.float64:
double = True
else:
double = False
if double:
self.field = DoubleField()
else:
self.field = FloatField()
else:
self.field = field
c = 1
for d in data.shape:
c *= d
divisor = biggest_divisor_smaller_than(c, 128)
shape = (c // divisor, divisor)
self.data = data.view(shape) # type: torch.Tensor
self.ndim = len(self.data.shape)
self.top_level_size = self.data.shape[self.dim]
rnd = numpy.random.RandomState(2021)
self.weights = self._generate_weight_matrix(rnd, self.n, self.k)
self.inverted_weights = self.field.invert(self.weights)
self.partial_n = self.top_level_size % self.n
self.partial_weights = self._generate_weight_matrix(rnd, self.partial_n, self.k)
self.partial_inverted_weights = self.field.invert(self.partial_weights)
self.redundancy_top_level_size = math.ceil(self.top_level_size / self.n) * self.k
redundancy_shape = tuple(self.redundancy_top_level_size if d == self.dim else s
for d, s in enumerate(self.data.shape))
self.redundancy = torch.zeros(redundancy_shape)
self.checksum = torch.zeros(self.top_level_size + self.redundancy_top_level_size)
self.detection_checksum = torch.sum(self.data)
self._update_redundancy()
self._update_checksum()
def _generate_weight_matrix(self, rnd, n, k):
weight_size = n + k
weights = self.field.random(rnd, weight_size, weight_size)
weights[:n, :n] = 0.
for i in range(n):
weights[i, i] = 1.
return weights
def _update_redundancy(self):
for start in range(0, self.top_level_size, self.n):
end = min(start + self.n, self.top_level_size)
redundancy_start = start // self.n * self.k
redundancy_end = redundancy_start + self.k
data_chunk = self.data[self._data_range(start, end)]
redundancy_chunk = self._calculate_redundancy(data_chunk)
self.redundancy[redundancy_start: redundancy_end] = redundancy_chunk
def _calculate_redundancy(self, data_chunk):
n = data_chunk.shape[self.dim]
if n == self.n:
weight_prefix = self.weights[:n, n:n + self.k]
else:
weight_prefix = self.partial_weights[:n, n:n + self.k]
transposed = data_chunk.transpose(self.dim, self.ndim - 1)
transposed_code = self.field.matmul(transposed, weight_prefix)
redundancy_chunk = transposed_code.transpose(self.ndim - 1, self.dim)
return redundancy_chunk
def _update_checksum(self):
self.checksum[:self.top_level_size] = self._checksum(self.data)
self.checksum[self.top_level_size: self.top_level_size + self.redundancy_top_level_size] = self._checksum(
self.redundancy
)
self.detection_checksum = torch.sum(self.data)
def _checksum(self, data):
return torch.sum(data, dim=tuple(d for d in range(len(self.data.shape)) if d != self.dim))
def check_and_fix_if_needed(self):
if self.detection_checksum == torch.sum(self.data):
return False
self._fix()
return True
def _calculate_checksum(self):
return torch.cat((self._checksum(self.data),
self._checksum(self.redundancy)), dim=0)
def _fix(self):
checksum = self._calculate_checksum()
for start in range(0, self.top_level_size, self.n):
end = min(start + self.n, self.top_level_size)
redundancy_start = start // self.n * self.k
checksum_indices = ((start, end),
(self.top_level_size + redundancy_start,
self.top_level_size + redundancy_start + self.k))
self._inner_fix(self.data[self._data_range(start, end)],
self.redundancy[self._data_range(redundancy_start, redundancy_start + self.k)],
checksum, checksum_indices)
self._update_checksum()
def _data_range(self, start, end):
return tuple(
slice(None) if d != self.dim else slice(
start, end
) for d in range(self.ndim)
)
def _inner_fix(self, data, redundancy, checksum, checksum_indices):
erasure = []
last_end = 0
for start, end in checksum_indices:
diff = torch.abs(checksum[start:end] - self.checksum[start: end])
nonzero = torch.nonzero(diff)
for corrupted_index in nonzero:
erasure.append((diff[corrupted_index], corrupted_index + last_end))
last_end = end - start
if len(erasure) >= self.k:
print(len(erasure), self.k)
erasure = sorted([int(i) for _, i in sorted(erasure, reverse=True)[:self.k]])
if erasure:
data_erasure = [e for e in erasure if e < data.shape[0]]
data[data_erasure] = self._recover(data, redundancy, erasure)[data_erasure]
redundancy[:] = self._calculate_redundancy(data)
def _recover(self, data, redundancy, erasure) -> torch.Tensor:
codeword = torch.cat((data, redundancy), self.dim)
codeword = codeword.transpose(self.dim, 0)
codeword_size = codeword.shape[0]
health = [i for i in range(codeword_size) if i not in erasure]
codeword[erasure] = codeword[health[:len(erasure)]]
codeword = codeword.transpose(0, self.dim)
codeword = torch.transpose(codeword, self.dim, self.ndim - 1)
n = data.shape[self.dim]
if n == self.n:
weights = self.weights.clone()
else:
weights = self.partial_weights.clone()
U = weights[:, health[:len(erasure)]]
U[:-self.k] -= weights[:-self.k, erasure]
U[-self.k:] = 0
V = torch.zeros(len(erasure), codeword_size)
for i, corrupted_index in enumerate(erasure):
V[i, corrupted_index] = 1
if self.use_woodbury:
patch = self._woodbury(U, V)
else:
weights[:-self.k, erasure] = weights[:-self.k, health[:len(erasure)]]
patch = self.field.invert(weights)
recovered = self.field.matmul(codeword, patch)
recovered = recovered.transpose(self.ndim - 1, 0)[:n].transpose(0, self.ndim - 1).transpose(self.ndim - 1, self.dim)
return recovered
def _woodbury(self, U, V):
n = U.shape[0] - self.k
C = torch.eye(U.shape[1])
if n == self.n:
inverted_weights = self.inverted_weights
else:
inverted_weights = self.partial_inverted_weights
return inverted_weights - (
self.field.matmul(
self.field.matmul(
self.field.matmul(inverted_weights, U),
self.field.invert(C + self.field.matmul(self.field.matmul(V, inverted_weights), U))
),
self.field.matmul(V, inverted_weights)
)
)
if __name__ == '__main__':
data = torch.rand(256, 2)
golden = data.clone()
esc = EfficientStructuralCoding(66, 32, data)
data[31, 0] = 10000
esc.redundancy[0, 0] = 0
esc.redundancy[-1, 0] = 0
esc.check_and_fix_if_needed()
print(torch.max(torch.abs(data - golden)))
# matrix = torch.rand((2, 3))
# square = torch.zeros((3, 3))
# square_inverse = torch.zeros((3, 3))
# square[:2, :] = matrix
# inverse = torch.pinverse(square)
# square_inverse = inverse
# print(square.matmul(square_inverse))
# A = torch.Tensor([[1, 2, 3, 0, 0],
# [3, 2, 1, 0, 0],
# [1, 5, 1, 0, 0]])
#
# B = torch.rand((5, 5))
# print(B)
# B_inverse = torch.inverse(B)
# print(B_inverse)
# AB = torch.matmul(A, B)
# print(AB)
# ABB_inverse = torch.matmul(AB, B_inverse)
# print(ABB_inverse)