-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhelpers_functional.py
175 lines (118 loc) · 6.44 KB
/
helpers_functional.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
from torch.nn.functional import fold, unfold
from torch import Tensor, empty#, einsum
def _pair(x):
if isinstance(x, int):
return (x, x)
return x
def pad(input, pad=(1,1,1,1), mode="constant", value=0.0):
# pad = (pad_left, pad_right, pad_up, pad_down)
if len(pad) == 2:
pad = (pad[0], pad[0], pad[1], pad[1])
input_shape = [input.size(0), input.size(1), input.size(2), input.size(3)]
input_shape[3] += (pad[0] + pad[1])
input_shape[2] += (pad[2] + pad[3])
i1 = pad[2]
j1 = pad[0]
i2 = input_shape[2] - pad[3]
j2 = input_shape[3] - pad[1]
result = empty(input_shape).fill_(value)
result[:,:,i1:i2,j1:j2] = input
return result
def conv2d(input: Tensor, weight: Tensor, bias=None, stride=1, padding=0, dilation=1, groups=1) -> Tensor:
# input is 4d tensor
stride = _pair(stride)
padding = _pair(padding)
dilation = _pair(dilation)
N = input.size(0)
H_in = input.size(-2)
W_in = input.size(-1)
kernel_size = (weight.size(-2), weight.size(-1))
C_out = weight.size(0)
H_out = int((H_in + 2 * padding[0] - dilation[0] * (kernel_size[0] - 1) - 1) / stride[0] + 1)
W_out = int((W_in + 2 * padding[1] - dilation[1] * (kernel_size[1] - 1) - 1) / stride[1] + 1)
unfolded = unfold(input, kernel_size=kernel_size, dilation=dilation, stride=stride, padding=padding)
#wxb = empty(N, C_out, unfolded.size(2))
#for ind, unfdd in enumerate(unfolded):
# wxb[ind] = weight.view(C_out, -1) @ unfdd + bias.view(-1,1)
#wxb = einsum('nij,njk->nik', weight.view(1, C_out, -1).repeat(N, 1, 1), unfolded) + bias.view(1, -1, 1).repeat(N,1,1)
wxb = weight.view(1, C_out, -1).repeat(N, 1, 1).matmul(unfolded) + bias.view(1, -1, 1).repeat(N,1,1)
return wxb.view(N, C_out, H_out, W_out)
def zero_internal_pad(x, pad=(1,1)):
x_shape = [x.size(0), x.size(1), x.size(2), x.size(3)]
x_shape[2] += (pad[0]*(x_shape[2]-1))
x_shape[3] += (pad[1]*(x_shape[3]-1))
res = empty(x_shape).fill_(0.0)
res[:,:,::pad[0]+1,::pad[1]+1] = x
return res
# TODO: groups not working
def conv_transpose2d(input: Tensor, weight: Tensor, bias=None, stride=(1,1), padding=(0,0), dilation=(1,1), groups=1, output_padding=0) -> Tensor:
# input is 4d tensor
stride = _pair(stride)
padding = _pair(padding)
output_padding = _pair(output_padding)
dilation = _pair(dilation)
N = input.size(0)
H_in = input.size(-2)
W_in = input.size(-1)
kernel_size = (weight.size(-2), weight.size(-1))
C_out = weight.size(1)
H_out = (H_in - 1) * stride[0] - 2 * padding[0] + dilation[0] * (kernel_size[0] - 1) + 1 + output_padding[0]
W_out = (W_in - 1) * stride[1] - 2 * padding[1] + dilation[1] * (kernel_size[1] - 1) + 1 + output_padding[1]
pad0 = (dilation[0] * (kernel_size[0] - 1) - padding[0])
pad1 = (dilation[1] * (kernel_size[1] - 1) - padding[1])
if (pad0<0) or (pad1<0):
raise ValueError("Invalid inputs, transposed convolution not possible")
if (stride[0]>1) or (stride[1]>1):
input = zero_internal_pad(input, pad=(stride[0]-1,stride[1]-1))
if (output_padding[0]>0) or (output_padding[1]>0):
input = pad(input, pad=(0,output_padding[1],0,output_padding[0]))
unfolded = unfold(input, kernel_size=kernel_size, dilation=dilation, stride=1, padding=(pad0,pad1))
w = weight.transpose(0,1).rot90(-2, [-2,-1])
wxb = unfolded.transpose(1, 2).matmul(w.reshape(w.size(0), -1).t()).transpose(1, 2) + bias.view(1, -1, 1).repeat(N,1,1)
res = wxb.view(N, C_out, H_out, W_out)
return res
def _grad_input_padding(grad_output, input_size, stride, padding, kernel_size, dilation=None):
if dilation is None:
dilation = [1] * len(stride)
input_size = list(input_size)
k = grad_output.dim() - 2
if len(input_size) == k + 2:
input_size = input_size[-k:]
if len(input_size) != k:
raise ValueError("input_size must have {} elements (got {})".format(k + 2, len(input_size)))
def dim_size(d):
return ((grad_output.size(d + 2) - 1) * stride[d] - 2 * padding[d] + 1 + dilation[d] * (kernel_size[d] - 1))
min_sizes = [dim_size(d) for d in range(k)]
max_sizes = [min_sizes[d] + stride[d] - 1 for d in range(k)]
for size, min_size, max_size in zip(input_size, min_sizes, max_sizes):
if size < min_size or size > max_size:
raise ValueError(
("requested an input grad size of {}, but valid sizes range "
"from {} to {} (for a grad_output of {})").format(input_size, min_sizes, max_sizes, grad_output.size()[2:]))
return tuple(input_size[d] - min_sizes[d] for d in range(k))
def conv2d_grad_input(input_shape, weight, grad_output, stride, padding, dilation, groups):
stride = _pair(stride)
padding = _pair(padding)
dilation = _pair(dilation)
kernel_size = (weight.shape[-2], weight.shape[-1])
if input_shape is None:
raise ValueError("conv2d_grad_input requires specifying an input_size")
grad_input_padding = _grad_input_padding(grad_output, input_shape, stride, padding, kernel_size, dilation)
return conv_transpose2d(input=grad_output, weight=weight, bias=None, stride=stride, padding=padding, output_padding=grad_input_padding, groups=groups, dilation=dilation)
def conv2d_weight(input, weight_size, grad_output, stride=1, padding=0, dilation=1, groups=1):
stride = _pair(stride)
padding = _pair(padding)
dilation = _pair(dilation)
in_channels = input.shape[1]
out_channels = grad_output.shape[1]
min_batch = input.shape[0]
grad_output = grad_output.contiguous().repeat(1, in_channels // groups, 1,
1)
grad_output = grad_output.contiguous().view(
grad_output.shape[0] * grad_output.shape[1], 1, grad_output.shape[2],
grad_output.shape[3])
input = input.contiguous().view(1, input.shape[0] * input.shape[1],
input.shape[2], input.shape[3])
grad_weight = conv2d(input, grad_output, None, dilation, padding, stride, in_channels * min_batch)
grad_weight = grad_weight.contiguous().view(min_batch, grad_weight.shape[1] // min_batch, grad_weight.shape[2], grad_weight.shape[3])
return grad_weight.sum(dim=0).view(in_channels // groups, out_channels, grad_weight.shape[2], grad_weight.shape[3]).transpose(0, 1).narrow(2, 0, weight_size[2]).narrow(3, 0, weight_size[3])