-
Notifications
You must be signed in to change notification settings - Fork 2
/
SparseJacobian.lua
277 lines (239 loc) · 8.42 KB
/
SparseJacobian.lua
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
nn.SparseJacobian = {}
function nn.SparseJacobian.backward (module, input, param, dparam)
local doparam = 0
if param then
doparam = 1
end
-- output deriv
module:forward(input)
local dout = module.output.new():resizeAs(module.output)
-- 1D view
local sdout = module.output.new(dout:storage(), 1, dout:nElement())
-- jacobian matrix to calculate
local jacobian
if doparam == 1 then
jacobian = torch.Tensor(param:nElement(), dout:nElement()):zero()
else
jacobian = torch.Tensor(input:size(1), dout:nElement()):zero()
end
for i=1,sdout:nElement() do
dout:zero()
sdout[i] = 1
module:zeroGradParameters()
local din = module:updateGradInput(input, dout)
module:accGradParameters(input, dout)
if doparam == 1 then
jacobian:select(2,i):copy(dparam)
else
jacobian:select(2,i):copy(din:select(2,2))
end
end
return jacobian
end
function nn.SparseJacobian.backwardUpdate (module, input, param)
-- output deriv
module:forward(input)
local dout = module.output.new():resizeAs(module.output)
-- 1D view
local sdout = module.output.new(dout:storage(),1,dout:nElement())
-- jacobian matrix to calculate
local jacobian = torch.Tensor(param:nElement(),dout:nElement()):zero()
-- original param
local params = module:parameters()
local origparams = {}
for j=1,#params do
table.insert(origparams, params[j]:clone())
end
for i=1,sdout:nElement() do
-- Reset parameters
for j=1,#params do
params[j]:copy(origparams[j])
end
dout:zero()
sdout[i] = 1
module:zeroGradParameters()
module:updateGradInput(input, dout)
module:accUpdateGradParameters(input, dout, 1)
jacobian:select(2,i):copy(param)
end
for j=1,#params do
params[j]:copy(origparams[j])
end
return jacobian
end
function nn.SparseJacobian.forward(module, input, param)
local doparam = 0
if param then
doparam = 1
end
param = param or input
-- perturbation amount
local small = 1e-6
-- 1D view of input
--local tst = param:storage()
local sin
if doparam == 1 then
sin = param.new(param):resize(param:nElement())
else
sin = input.new(input):select(2,2)
end
local out = module:forward(input)
-- jacobian matrix to calculate
local jacobian
if doparam == 1 then
jacobian = torch.Tensor():resize(param:nElement(),
out:nElement())
else
jacobian = torch.Tensor():resize(input:size(1),
out:nElement())
end
local outa = torch.Tensor(jacobian:size(2))
local outb = torch.Tensor(jacobian:size(2))
for i=1,sin:nElement() do
sin[i] = sin[i] - small
outa:copy(module:forward(input))
sin[i] = sin[i] + 2*small
outb:copy(module:forward(input))
sin[i] = sin[i] - small
outb:add(-1,outa):div(2*small)
jacobian:select(1,i):copy(outb)
end
return jacobian
end
function nn.SparseJacobian.forwardUpdate(module, input, param)
-- perturbation amount
local small = 1e-6
-- 1D view of input
--local tst = param:storage()
local sin = param.new(param):resize(param:nElement())--param.new(tst,1,tst:size())
-- jacobian matrix to calculate
local jacobian = torch.Tensor():resize(param:nElement(),module:forward(input):nElement())
local outa = torch.Tensor(jacobian:size(2))
local outb = torch.Tensor(jacobian:size(2))
for i=1,sin:nElement() do
sin[i] = sin[i] - small
outa:copy(module:forward(input))
sin[i] = sin[i] + 2*small
outb:copy(module:forward(input))
sin[i] = sin[i] - small
outb:add(-1,outa):div(2*small)
jacobian:select(1,i):copy(outb)
jacobian:select(1,i):mul(-1)
jacobian:select(1,i):add(sin[i])
end
return jacobian
end
function nn.SparseJacobian.testJacobian (module, input, minval, maxval)
minval = minval or -2
maxval = maxval or 2
local inrange = maxval - minval
input:select(2,2):copy(torch.rand(input:size(1)):mul(inrange):add(minval))
local jac_fprop = nn.SparseJacobian.forward(module,input)
local jac_bprop = nn.SparseJacobian.backward(module,input)
local error = jac_fprop-jac_bprop
return error:abs():max()
end
function nn.SparseJacobian.testJacobianParameters (module, input, param, dparam, minval, maxval)
minval = minval or -2
maxval = maxval or 2
local inrange = maxval - minval
input:select(2,2):copy(torch.rand(input:size(1)):mul(inrange):add(minval))
param:copy(torch.rand(param:nElement()):mul(inrange):add(minval))
local jac_bprop = nn.SparseJacobian.backward(module, input, param, dparam)
local jac_fprop = nn.SparseJacobian.forward(module, input, param)
local error = jac_fprop - jac_bprop
return error:abs():max()
end
function nn.SparseJacobian.testJacobianUpdateParameters (module, input, param, minval, maxval)
minval = minval or -2
maxval = maxval or 2
local inrange = maxval - minval
input:select(2,2):copy(torch.rand(input:size(1)):mul(inrange):add(minval))
param:copy(torch.rand(param:nElement()):mul(inrange):add(minval))
local params_bprop = nn.SparseJacobian.backwardUpdate(module, input, param)
local params_fprop = nn.SparseJacobian.forwardUpdate(module, input, param)
local error = params_fprop - params_bprop
return error:abs():max()
end
function nn.SparseJacobian.testIO(module,input, minval, maxval)
minval = minval or -2
maxval = maxval or 2
local inrange = maxval - minval
-- run module
module:forward(input)
local go = module.output:clone():copy(torch.rand(module.output:nElement()):mul(inrange):add(minval))
module:zeroGradParameters()
module:updateGradInput(input,go)
module:accGradParameters(input,go)
local fo = module.output:clone()
local bo = module.gradInput:clone()
-- write module
local f = torch.DiskFile('tmp.bin','w'):binary()
f:writeObject(module)
f:close()
-- read module
local m = torch.DiskFile('tmp.bin'):binary():readObject()
m:forward(input)
m:zeroGradParameters()
m:updateGradInput(input,go)
m:accGradParameters(input,go)
-- cleanup
os.remove('tmp.bin')
local fo2 = m.output:clone()
local bo2 = m.gradInput:clone()
local errf = fo - fo2
local errb = bo - bo2
return errf:abs():max(), errb:abs():max()
end
function nn.SparseJacobian.testAllUpdate(module, input, weight, gradWeight)
local gradOutput
local lr = torch.uniform(0.1, 1)
local errors = {}
-- accGradParameters
local maccgp = module:clone()
local weightc = maccgp[weight]:clone()
maccgp:forward(input)
gradOutput = torch.rand(maccgp.output:size())
maccgp:zeroGradParameters()
maccgp:updateGradInput(input, gradOutput)
maccgp:accGradParameters(input, gradOutput)
maccgp:updateParameters(lr)
errors["accGradParameters"] = (weightc-maccgp[gradWeight]*lr-maccgp[weight]):norm()
-- accUpdateGradParameters
local maccugp = module:clone()
maccugp:forward(input)
maccugp:updateGradInput(input, gradOutput)
maccugp:accUpdateGradParameters(input, gradOutput, lr)
errors["accUpdateGradParameters"] = (maccugp[weight]-maccgp[weight]):norm()
-- shared, accGradParameters
local macsh1 = module:clone()
local macsh2 = module:clone()
macsh2:share(macsh1, weight)
macsh1:forward(input)
macsh2:forward(input)
macsh1:zeroGradParameters()
macsh2:zeroGradParameters()
macsh1:updateGradInput(input, gradOutput)
macsh2:updateGradInput(input, gradOutput)
macsh1:accGradParameters(input, gradOutput)
macsh2:accGradParameters(input, gradOutput)
macsh1:updateParameters(lr)
macsh2:updateParameters(lr)
local err = (weightc-maccgp[gradWeight]*(lr*2)-macsh1[weight]):norm()
err = err + (weightc-maccgp[gradWeight]*(lr*2)-macsh2[weight]):norm()
errors["accGradParameters [shared]"] = err
-- shared, accUpdateGradParameters
local macshu1 = module:clone()
local macshu2 = module:clone()
macshu2:share(macshu1, weight)
macshu1:forward(input)
macshu2:forward(input)
macshu1:updateGradInput(input, gradOutput)
macshu2:updateGradInput(input, gradOutput)
macshu1:accUpdateGradParameters(input, gradOutput, lr)
macshu2:accUpdateGradParameters(input, gradOutput, lr)
err = (weightc-maccgp[gradWeight]*(lr*2)-macshu1[weight]):norm()
err = err + (weightc-maccgp[gradWeight]*(lr*2)-macshu2[weight]):norm()
errors["accUpdateGradParameters [shared]"] = err
return errors
end