-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlayers.py
446 lines (374 loc) · 19.3 KB
/
layers.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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Function
from torch import Tensor
from torch.nn.modules.conv import _ConvNd
from torch.nn.modules.utils import _pair
import math
## Feedback Alignment Linear
class FALinearFunc(Function):
# Note that both forward and backward are @staticmethods
@staticmethod
# bias is an optional argument
def forward(ctx, input, weight, weight_fb, bias=None):
ctx.save_for_backward(input, weight, weight_fb, bias)
output = input.mm(weight.t())
if bias is not None:
output += bias.unsqueeze(0).expand_as(output)
return output
# This function has only a single output, so it gets only one gradient
@staticmethod
def backward(ctx, grad_output):
# This is a pattern that is very convenient - at the top of backward
# unpack saved_tensors and initialize all gradients w.r.t. inputs to
# None. Thanks to the fact that additional trailing Nones are
# ignored, the return statement is simple even when the function has
# optional inputs.
input, weight, weight_fb, bias = ctx.saved_tensors
grad_input = grad_weight = grad_weight_fb = grad_bias = None
# These needs_input_grad checks are optional and there only to
# improve efficiency. If you want to make your code simpler, you can
# skip them. Returning gradients for inputs that don't require it is
# not an error.
if ctx.needs_input_grad[0]:
grad_input = grad_output.mm(weight_fb) #weight_fb
if ctx.needs_input_grad[1]:
grad_weight = grad_output.t().mm(input)
# if ctx.needs_input_grad[2]:
# grad_weight_fb = grad_weight
if bias is not None and ctx.needs_input_grad[3]:
grad_bias = grad_output.sum(0)
return grad_input, grad_weight, grad_weight_fb, grad_bias
class FALinear(nn.Module):
__constants__ = ['in_features', 'out_features']
in_features: int
out_features: int
weight: Tensor
def __init__(self, in_features: int, out_features: int, bias: bool = True) -> None:
super(FALinear, self).__init__()
self.in_features = in_features
self.out_features = out_features
self.weight = nn.Parameter(torch.Tensor(out_features, in_features))
#self.weight_fb = nn.Parameter(torch.Tensor(out_features, in_features), requires_grad=False)
self.register_buffer('weight_fb', torch.Tensor(out_features, in_features))
if bias:
self.bias = nn.Parameter(torch.Tensor(out_features))
else:
self.register_parameter('bias', None)
self.reset_parameters()
def reset_parameters(self) -> None:
nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5))
nn.init.kaiming_uniform_(self.weight_fb, a=math.sqrt(5)) # feedback weight
if self.bias is not None:
fan_in, _ = nn.init._calculate_fan_in_and_fan_out(self.weight)
bound = 1 / math.sqrt(fan_in)
nn.init.uniform_(self.bias, -bound, bound)
def forward(self, input: Tensor) -> Tensor:
return FALinearFunc.apply(input, self.weight, self.weight_fb, self.bias)
def extra_repr(self) -> str:
return 'in_features={}, out_features={}, bias={}'.format(
self.in_features, self.out_features, self.bias is not None
)
## Feedback Alignment Conv2d
class FAConv2dFunc(Function):
# Note that both forward and backward are @staticmethods
@staticmethod
def forward(ctx, input, weight, weight_fb, bias=None, stride=1, padding=0, dilation=1, groups=1):
ctx.save_for_backward(input, weight, weight_fb, bias) # Add weight for backward
ctx.stride = stride
ctx.padding = padding
ctx.dilation = dilation
ctx.groups = groups
output = F.conv2d(input, weight, bias, stride, padding, dilation, groups)
return output
# This function has only a single output, so it gets only one gradient
@staticmethod
def backward(ctx, grad_output):
# This is a pattern that is very convenient - at the top of backward
# unpack saved_tensors and initialize all gradients w.r.t. inputs to
# None. Thanks to the fact that additional trailing Nones are
# ignored, the return statement is simple even when the function has
# optional inputs.
input, weight, weight_fb, bias = ctx.saved_tensors # Weight for backward
stride = ctx.stride
padding = ctx.padding
dilation = ctx.dilation
groups = ctx.groups
grad_input = grad_weight = grad_weight_fb = grad_bias = None
# These needs_input_grad checks are optional and there only to
# improve efficiency. If you want to make your code simpler, you can
# skip them. Returning gradients for inputs that don't require it is
# not an error.
if ctx.needs_input_grad[0]: ## use weight_fb
grad_input = torch.nn.grad.conv2d_input(input.shape, weight_fb, grad_output, stride, padding, dilation, groups)
if ctx.needs_input_grad[1]:
grad_weight = torch.nn.grad.conv2d_weight(input, weight.shape, grad_output, stride, padding, dilation, groups)
# if ctx.needs_input_grad[2]:
# grad_weight_fb = grad_weight
if bias is not None and ctx.needs_input_grad[3]:
grad_bias = grad_output.sum((0,2,3))
return grad_input, grad_weight, grad_weight_fb, grad_bias, None, None, None, None
class FAConv2d(_ConvNd):
def __init__(self, in_channels, out_channels, kernel_size, stride=1,
padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros'):
kernel_size = _pair(kernel_size)
stride = _pair(stride)
padding = _pair(padding)
dilation = _pair(dilation)
super(FAConv2d, self).__init__(in_channels, out_channels, kernel_size, stride, padding, dilation,
False, _pair(0), groups, bias, padding_mode)
#self.weight_fb = nn.Parameter(torch.Tensor(out_channels, in_channels // groups, *kernel_size), requires_grad=False)
self.register_buffer('weight_fb', torch.Tensor(out_channels, in_channels // groups, *kernel_size))
#Initialize
nn.init.kaiming_uniform_(self.weight_fb, a=math.sqrt(5))
def forward(self, input):
if self.padding_mode != 'zeros':
return FAConv2dFunc.apply(F.pad(input, self._reversed_padding_repeated_twice, mode=self.padding_mode),
self.weight, self.weight_fb, self.bias, self.stride, _pair(0), self.dilation, self.groups)
return FAConv2dFunc.apply(input, self.weight, self.weight_fb, self.bias, self.stride,
self.padding, self.dilation, self.groups)
## URFB Linear
class UfLinearFunc(Function):
# Note that both forward and backward are @staticmethods
@staticmethod
# bias is an optional argument
def forward(ctx, input, weight, weight_fb, bias=None):
ctx.save_for_backward(input, weight, weight_fb, bias)
output = input.mm(weight.t())
if bias is not None:
output += bias.unsqueeze(0).expand_as(output)
return output
# This function has only a single output, so it gets only one gradient
@staticmethod
def backward(ctx, grad_output):
# This is a pattern that is very convenient - at the top of backward
# unpack saved_tensors and initialize all gradients w.r.t. inputs to
# None. Thanks to the fact that additional trailing Nones are
# ignored, the return statement is simple even when the function has
# optional inputs.
input, weight, weight_fb, bias = ctx.saved_tensors
grad_input = grad_weight = grad_weight_fb = grad_bias = None
# These needs_input_grad checks are optional and there only to
# improve efficiency. If you want to make your code simpler, you can
# skip them. Returning gradients for inputs that don't require it is
# not an error.
if ctx.needs_input_grad[0]:
grad_input = grad_output.mm(weight_fb) #weight_fb
if ctx.needs_input_grad[1]:
grad_weight = grad_output.t().mm(input)
if ctx.needs_input_grad[2]:
grad_weight_fb = grad_weight
if bias is not None and ctx.needs_input_grad[3]:
grad_bias = grad_output.sum(0)
return grad_input, grad_weight, grad_weight_fb, grad_bias
class UfLinear(nn.Module):
__constants__ = ['in_features', 'out_features']
in_features: int
out_features: int
weight: Tensor
def __init__(self, in_features: int, out_features: int, bias: bool = True) -> None:
super(UfLinear, self).__init__()
self.in_features = in_features
self.out_features = out_features
self.weight = nn.Parameter(torch.Tensor(out_features, in_features))
self.weight_fb = nn.Parameter(torch.Tensor(out_features, in_features)) # feedbak weight
if bias:
self.bias = nn.Parameter(torch.Tensor(out_features))
else:
self.register_parameter('bias', None)
self.reset_parameters()
def reset_parameters(self) -> None:
nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5))
nn.init.kaiming_uniform_(self.weight_fb, a=math.sqrt(5)) # feedback weight
if self.bias is not None:
fan_in, _ = nn.init._calculate_fan_in_and_fan_out(self.weight)
bound = 1 / math.sqrt(fan_in)
nn.init.uniform_(self.bias, -bound, bound)
def forward(self, input: Tensor) -> Tensor:
return UfLinearFunc.apply(input, self.weight, self.weight_fb, self.bias)
def extra_repr(self) -> str:
return 'in_features={}, out_features={}, bias={}'.format(
self.in_features, self.out_features, self.bias is not None
)
## URFB Conv2d
class UfConv2dFunc(Function):
# Note that both forward and backward are @staticmethods
@staticmethod
def forward(ctx, input, weight, weight_fb, bias=None, stride=1, padding=0, dilation=1, groups=1):
ctx.save_for_backward(input, weight, weight_fb, bias) # Add weight for backward
ctx.stride = stride
ctx.padding = padding
ctx.dilation = dilation
ctx.groups = groups
output = F.conv2d(input, weight, bias, stride, padding, dilation, groups)
return output
# This function has only a single output, so it gets only one gradient
@staticmethod
def backward(ctx, grad_output):
# This is a pattern that is very convenient - at the top of backward
# unpack saved_tensors and initialize all gradients w.r.t. inputs to
# None. Thanks to the fact that additional trailing Nones are
# ignored, the return statement is simple even when the function has
# optional inputs.
input, weight, weight_fb, bias = ctx.saved_tensors # Weight for backward
stride = ctx.stride
padding = ctx.padding
dilation = ctx.dilation
groups = ctx.groups
grad_input = grad_weight = grad_weight_fb = grad_bias = None
# These needs_input_grad checks are optional and there only to
# improve efficiency. If you want to make your code simpler, you can
# skip them. Returning gradients for inputs that don't require it is
# not an error.
if ctx.needs_input_grad[0]: ## use weight_fb
grad_input = torch.nn.grad.conv2d_input(input.shape, weight_fb, grad_output, stride, padding, dilation, groups)
if ctx.needs_input_grad[1]:
grad_weight = torch.nn.grad.conv2d_weight(input, weight.shape, grad_output, stride, padding, dilation, groups)
if ctx.needs_input_grad[2]:
grad_weight_fb = grad_weight
if bias is not None and ctx.needs_input_grad[3]:
grad_bias = grad_output.sum((0,2,3))
return grad_input, grad_weight, grad_weight_fb, grad_bias, None, None, None, None
class UfConv2d(_ConvNd):
def __init__(self, in_channels, out_channels, kernel_size, stride=1,
padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros'):
kernel_size = _pair(kernel_size)
stride = _pair(stride)
padding = _pair(padding)
dilation = _pair(dilation)
super(UfConv2d, self).__init__(in_channels, out_channels, kernel_size, stride, padding, dilation,
False, _pair(0), groups, bias, padding_mode)
self.weight_fb = nn.Parameter(torch.Tensor(
out_channels, in_channels // groups, *kernel_size))
#Initialize
#self.weight_fb = self.weight # Same as normal backprop
nn.init.kaiming_uniform_(self.weight_fb, a=math.sqrt(5))
def forward(self, input):
if self.padding_mode != 'zeros':
return UfConv2dFunc.apply(F.pad(input, self._reversed_padding_repeated_twice, mode=self.padding_mode),
self.weight, self.weight_fb, self.bias, self.stride, _pair(0), self.dilation, self.groups)
return UfConv2dFunc.apply(input, self.weight, self.weight_fb, self.bias, self.stride,
self.padding, self.dilation, self.groups)
# USFB Linear
class UsLinearFunc(Function):
# Note that both forward and backward are @staticmethods
@staticmethod
# bias is an optional argument
def forward(ctx, input, weight, weight_fb, bias=None):
ctx.save_for_backward(input, weight, weight_fb, bias)
output = input.mm(weight.t())
if bias is not None:
output += bias.unsqueeze(0).expand_as(output)
return output
# This function has only a single output, so it gets only one gradient
@staticmethod
def backward(ctx, grad_output):
# This is a pattern that is very convenient - at the top of backward
# unpack saved_tensors and initialize all gradients w.r.t. inputs to
# None. Thanks to the fact that additional trailing Nones are
# ignored, the return statement is simple even when the function has
# optional inputs.
input, weight, weight_fb, bias = ctx.saved_tensors
grad_input = grad_weight = grad_weight_fb = grad_bias = None
# These needs_input_grad checks are optional and there only to
# improve efficiency. If you want to make your code simpler, you can
# skip them. Returning gradients for inputs that don't require it is
# not an error.
if ctx.needs_input_grad[0]:
grad_input = grad_output.mm(torch.sign(weight_fb))
if ctx.needs_input_grad[1]:
grad_weight = grad_output.t().mm(input)
if ctx.needs_input_grad[2]:
grad_weight_fb = grad_weight
if bias is not None and ctx.needs_input_grad[3]:
grad_bias = grad_output.sum(0)
return grad_input, grad_weight, grad_weight_fb, grad_bias
class UsLinear(nn.Module):
__constants__ = ['in_features', 'out_features']
in_features: int
out_features: int
weight: Tensor
def __init__(self, in_features: int, out_features: int, bias: bool = True) -> None:
super(UsLinear, self).__init__()
self.in_features = in_features
self.out_features = out_features
self.weight = nn.Parameter(torch.Tensor(out_features, in_features))
self.weight_fb = nn.Parameter(torch.Tensor(out_features, in_features)) # feedbak weight
if bias:
self.bias = nn.Parameter(torch.Tensor(out_features))
else:
self.register_parameter('bias', None)
self.reset_parameters()
def reset_parameters(self) -> None:
nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5))
nn.init.kaiming_uniform_(self.weight_fb, a=math.sqrt(5)) # feedback weight
if self.bias is not None:
fan_in, _ = nn.init._calculate_fan_in_and_fan_out(self.weight)
bound = 1 / math.sqrt(fan_in)
nn.init.uniform_(self.bias, -bound, bound)
def forward(self, input: Tensor) -> Tensor:
return UsLinearFunc.apply(input, self.weight, self.weight_fb, self.bias)
def extra_repr(self) -> str:
return 'in_features={}, out_features={}, bias={}'.format(
self.in_features, self.out_features, self.bias is not None
)
## USFB Conv2d
class UsConv2dFunc(Function):
# Note that both forward and backward are @staticmethods
@staticmethod
def forward(ctx, input, weight, weight_fb, bias=None, stride=1, padding=0, dilation=1, groups=1):
ctx.save_for_backward(input, weight, weight_fb, bias) # Add weight for backward
ctx.stride = stride
ctx.padding = padding
ctx.dilation = dilation
ctx.groups = groups
output = F.conv2d(input, weight, bias, stride, padding, dilation, groups)
return output
# This function has only a single output, so it gets only one gradient
@staticmethod
def backward(ctx, grad_output):
# This is a pattern that is very convenient - at the top of backward
# unpack saved_tensors and initialize all gradients w.r.t. inputs to
# None. Thanks to the fact that additional trailing Nones are
# ignored, the return statement is simple even when the function has
# optional inputs.
input, weight, weight_fb, bias = ctx.saved_tensors # Weight for backward
stride = ctx.stride
padding = ctx.padding
dilation = ctx.dilation
groups = ctx.groups
grad_input = grad_weight = grad_weight_fb = grad_bias = None
# These needs_input_grad checks are optional and there only to
# improve efficiency. If you want to make your code simpler, you can
# skip them. Returning gradients for inputs that don't require it is
# not an error.
if ctx.needs_input_grad[0]: ## use weight_fb
grad_input = torch.nn.grad.conv2d_input(input.shape, torch.sign(weight_fb), grad_output, stride, padding, dilation, groups)
if ctx.needs_input_grad[1]:
grad_weight = torch.nn.grad.conv2d_weight(input, weight.shape, grad_output, stride, padding, dilation, groups)
if ctx.needs_input_grad[2]:
grad_weight_fb = grad_weight
if bias is not None and ctx.needs_input_grad[3]:
grad_bias = grad_output.sum((0,2,3))
return grad_input, grad_weight, grad_weight_fb, grad_bias, None, None, None, None
class UsConv2d(_ConvNd):
def __init__(self, in_channels, out_channels, kernel_size, stride=1,
padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros'):
kernel_size = _pair(kernel_size)
stride = _pair(stride)
padding = _pair(padding)
dilation = _pair(dilation)
super(UsConv2d, self).__init__(in_channels, out_channels, kernel_size, stride, padding, dilation,
False, _pair(0), groups, bias, padding_mode)
self.weight_fb = nn.Parameter(torch.Tensor(
out_channels, in_channels // groups, *kernel_size))
#Initialize
#self.weight_fb = self.weight # Same as normal backprop
nn.init.kaiming_uniform_(self.weight_fb, a=math.sqrt(5))
def forward(self, input):
if self.padding_mode != 'zeros':
return UsConv2dFunc.apply(F.pad(input, self._reversed_padding_repeated_twice, mode=self.padding_mode),
self.weight, self.weight_fb, self.bias, self.stride, _pair(0), self.dilation, self.groups)
return UsConv2dFunc.apply(input, self.weight, self.weight_fb, self.bias, self.stride,
self.padding, self.dilation, self.groups)