- Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathdiff.lua
More file actions
Latest commit
321 lines (293 loc) · 10.6 KB
/
Copy pathdiff.lua
File metadata and controls
321 lines (293 loc) · 10.6 KB
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
--------------------------------------------------------------------------------
-- Automatic differentiation module.
--
-- Copyright (C) 2011-2016 Stefano Peluchetti. All rights reserved.
--------------------------------------------------------------------------------
-- TODO: Specialized gamma, loggamma, beta, logbeta.
-- TODO: Introduce specialized matrix multiply, inverse, ecc ecc using BLAS
-- TODO: (when available) based on the results summarized in Mike Giles paper.
-- PERF: We considered one-shot version with matrix-tape which computes the
-- PERF: gradient in one function call but gains where not substantial and
-- PERF: memory management is more complicated. Probably better to just
-- PERF: introduce reverse-mode differentiation directly.
localffi=require"ffi"
localxsys=require"xsys"
localmath=require"sci.math"
localtype=type
local
abs, acos, asin, atan, atan2, ceil, cos, cosh, deg, exp, floor, fmod, frexp,
huge, ldexp, log, log10, max, min, modf, pi, pow, rad, random, randomseed, sin,
sinh, sqrt, tan, tanh,
round, step, sign,
phi, iphi, gamma, loggamma, logbeta, beta
=xsys.from(math, [[
abs, acos, asin, atan, atan2, ceil, cos, cosh, deg, exp, floor, fmod, frexp,
huge, ldexp, log, log10, max, min, modf, pi, pow, rad, random, randomseed, sin,
sinh, sqrt, tan, tanh,
round, step, sign,
phi, iphi, gamma, loggamma, logbeta, beta
]])
-- Forward mode, single directional derivative ---------------------------------
localdn-- Dual number: value + adjoint value.
-- Modified from sci.math, works *only* with dual number type.
localdngamma, dnloggamma
do
-- r(10).
localgamma_r10=10.900511
-- dk[0], ..., dk[10].
localgamma_dk=ffi.new("double[11]",
2.48574089138753565546e-5,
1.05142378581721974210,
-3.45687097222016235469,
4.51227709466894823700,
-2.98285225323576655721,
1.05639711577126713077,
-1.95428773191645869583e-1,
1.70970543404441224307e-2,
-5.71926117404305781283e-4,
4.63399473359905636708e-6,
-2.71994908488607703910e-9
)
localgamma_c=2*sqrt(exp(1)/pi)
-- Lanczos approximation, see:
-- Pugh[2004]: AN ANALYSIS OF THE LANCZOS GAMMA APPROXIMATION
-- http://bh0.physics.ubc.ca/People/matt/Doc/ThesesOthers/Phd/pugh.pdf
-- page 116 for optimal formula and coefficients. Theoretical accuracy of
-- 16 digits is likely in practice to be around 14.
-- Domain: R except 0 and negative integers.
dngamma=function(z)
-- Reflection formula to handle negative z plane.
-- Better to branch at z < 0 as some probabilistic use cases only consider
-- the case z >= 0.
ifz<0then
returnpi/((pi*z):sin()*dngamma(1-z))
end
localsum=gamma_dk[0]
sum=sum+gamma_dk[1]/(z+0)
sum=sum+gamma_dk[2]/(z+1)
sum=sum+gamma_dk[3]/(z+2)
sum=sum+gamma_dk[4]/(z+3)
sum=sum+gamma_dk[5]/(z+4)
sum=sum+gamma_dk[6]/(z+5)
sum=sum+gamma_dk[7]/(z+6)
sum=sum+gamma_dk[8]/(z+7)
sum=sum+gamma_dk[9]/(z+8)
sum=sum+gamma_dk[10]/(z+9)
returngamma_c*((z+gamma_r10-0.5)/exp(1))^(z-0.5)*sum
end
-- Returns log(abs(gamma(z))).
-- Domain: R except 0 and negative integers.
dnloggamma=function(z)
ifz<0then
returnlog(pi) - (pi*z):sin():abs():log() -dnloggamma(1-z)
end
localsum=gamma_dk[0]
sum=sum+gamma_dk[1]/(z+0)
sum=sum+gamma_dk[2]/(z+1)
sum=sum+gamma_dk[3]/(z+2)
sum=sum+gamma_dk[4]/(z+3)
sum=sum+gamma_dk[5]/(z+4)
sum=sum+gamma_dk[6]/(z+5)
sum=sum+gamma_dk[7]/(z+6)
sum=sum+gamma_dk[8]/(z+7)
sum=sum+gamma_dk[9]/(z+8)
sum=sum+gamma_dk[10]/(z+9)
-- For z >= 0 gamma function is positive, no abs() required.
returnlog(gamma_c) + (z-0.5)*(z+gamma_r10-0.5):log()
- (z-0.5) +sum:log()
end
end
-- Domain: a > 0 and b > 0.
localfunctiondnlogbeta(a, b)
ifa<=0orb<=0thenreturn0/0end
locallga=type(a) =="number" andloggamma(a) ordnloggamma(a)
locallgb=type(b) =="number" andloggamma(b) ordnloggamma(b)
returnlga+lgb-dnloggamma(a+b)
end
-- Domain: a > 0 and b > 0.
localfunctiondnbeta(a, b)
returndnlogbeta(a, b):exp()
end
-- Derivative of phi function:
localfunctiondphi(x)
return (1/sqrt(2*pi))*exp(-0.5*x^2)
end
-- Use branchless optimization whenever finite values:
localfunctiondnmax(x, y)
x, y=dn(x), dn(y)
ifmax(abs(x._v), abs(y._v)) ==1/0then
returnx>=yandxory
else-- Branchless optimization.
localz=step(y._v-x._v) -- 1 if y >= x, 0 otherwise.
returndn(z*y._v+ (1-z)*x._v, z*y._a+ (1-z)*x._a)
end
end
-- Use branchless optimization whenever finite values:
localfunctiondnmin(x, y)
x, y=dn(x), dn(y)
ifmax(abs(x._v), abs(y._v)) ==1/0then
returnx<=yandxory
else-- Branchless optimization.
localz=step(x._v-y._v) -- 1 if x >= y, 0 otherwise.
returndn(z*y._v+ (1-z)*x._v, z*y._a+ (1-z)*x._a)
end
end
-- Note: dual numbers are immutable: new ones generated by operators.
localdn_mt= {
__unm=function(x)
returndn(-x._v, -x._a)
end,
__add=function(x, y) x, y=dn(x), dn(y)
returndn(x._v+y._v, x._a+y._a)
end,
__sub=function(x, y) x, y=dn(x), dn(y)
returndn(x._v-y._v, x._a-y._a)
end,
__mul=function(x, y) x, y=dn(x), dn(y)
returndn(x._v*y._v, x._a*y._v+y._a*x._v)
end,
__div=function(x, y) x, y=dn(x), dn(y)
returndn(x._v/y._v, (x._a*y._v-y._a*x._v)/y._v^2)
end,
__pow=function(x, y) -- Optimized version.
iftype(y) =="number" then
returndn(x._v^y, y*x._v^(y-1)*x._a)
elseiftype(x) =="number" then
returndn(x^y._v, x^y._v*log(x)*y._a)
else
returndn(x._v^y._v, x._v^y._v*(log(x._v)*y._a+y._v/x._v*x._a))
end
end,
__eq=function(x, y) x, y=dn(x), dn(y)
returnx._v==y._v
end,
__lt=function(x, y) x, y=dn(x), dn(y)
returnx._v<y._v
end,
__le=function(x, y) x, y=dn(x), dn(y)
returnx._v<=y._v
end,
__tostring=function(x)
returntostring(x._v) -- Better to mimic behavior of numbers.
end,
__tonumber=function(x) -- Honored only by xsys.string.width.
returntonumber(x._v)
end,
copy=function(x)
returndn(x)
end,
val=function(x)
returnx._v
end,
adj=function(x)
returnx._a
end,
sin=function(x) returndn(sin(x._v), x._a*cos(x._v)) end,
cos=function(x) returndn(cos(x._v), x._a*(-sin(x._v))) end,
tan=function(x) returndn(tan(x._v), x._a*(1+tan(x._v)^2)) end,
asin=function(x) returndn(asin(x._v), x._a/sqrt(1-x._v^2)) end,
acos=function(x) returndn(acos(x._v), -x._a/sqrt(1-x._v^2)) end,
atan=function(x) returndn(atan(x._v), x._a/(1+x._v^2)) end,
sinh=function(x) returndn(sinh(x._v), x._a*cosh(x._v)) end,
cosh=function(x) returndn(cosh(x._v), x._a*sinh(x._v)) end,
tanh=function(x) returndn(tanh(x._v), x._a*(1-tanh(x._v)^2)) end,
exp=function(x) returndn(exp(x._v), x._a*exp(x._v)) end,
log=function(x) returndn(log(x._v), x._a/x._v) end,
sqrt=function(x) returndn(sqrt(x._v), x._a/(2*sqrt(x._v))) end,
abs=function(x) returndn(abs(x._v), x._a*sign(x._v)) end,
-- Stick to dn type to improve type stability:
floor=function(x) returndn(floor(x._v), 0) end,
ceil=function(x) returndn(ceil(x._v), 0) end,
-- Stick to dn type to improve type stability:
round=function(x) returndn(round(x._v), 0) end,
step=function(x) returndn(step(x._v), 0) end,
sign=function(x) returndn(sign(x._v), 0) end,
gamma=function(x) returndngamma(x) end,
loggamma=function(x) returndnloggamma(x) end,
beta=function(x, y) returndnbeta(x, y) end,
logbeta=function(x, y) returndnlogbeta(x, y) end,
phi=function(x) returndn(phi(x._v), x._a*dphi(x._v)) end,
iphi=function(x) localy=iphi(x._v); returndn(y, x._a/dphi(y)) end,
max=dnmax,
min=dnmin,
}
dn_mt.__index=dn_mt
-- Note: _v comes first. This allows to construct a dual number from a number
-- using dn(number) => adjoint part correctly initialized to 0.
dn=ffi.metatype("struct { double _v, _a; }", dn_mt)
-- To improve type stability we always pass all arguments wrt differentiation
-- will take place as dual numbers, only one of which will have adj part
-- equal to 1.
localpderf_template=xsys.template[[
local f, dn = f, dn
| local args = { }
| for i=1,n do
| args[i] = "x"..i
| end
| args = concat(args, ",")
return function(${args})
| local dargs = args..","
| for i=1,#dxi do
| local dx = dxi[i]
| dargs = dargs:gsub("x"..dx..",", "dn(x"..dx..",0),")
| end
| dargs = dargs:gsub(",$", "")
| local retadj = { }
| for i=1,#dxi do
| local from, to = "dn%(x"..dxi[i]..",0%)", "dn%(x"..dxi[i]..",1%)"
local y${i} = dn(f(${dargs:gsub(from, to)}))
| retadj[i] = "y"..i..":adj()"
| end
return y1:val(),${concat(retadj, ",")}
end
]]
localfunctionderivativef(f, n, ...)
assert(1<=n, "function's argument # must be positive")
localdxi
ifselect("#", ...) ==0then
dxi= { }
fori=1,ndo
dxi[i] =i
end
else
dxi= { ... }
fori=1,#dxido
localdx=dxi[i]
assert(dx<=n, "differentiating variable outside function's argument #")
end
end
localsrc=pderf_template({ n=n, dxi=dxi, concat=table.concat })
returnxsys.exec(src, "<derivative>", { f=f, dn=dn })
end
-- For forward mode differentiation we could just use grad(f, x, y) to return
-- f(x) and set y to the gradient of f(x), but gradients are best computed in
-- reverse mode differentiation, and a stack will need to be allocated for f,
-- the length of which (it's growth-able) likely depends on the f itself hence
-- it's best stored via a closure.
localfunctiongradientf(f, n)
localalgdn=require("sci.alg").typeof(dn, dn)
localxd=algdn.vec(n)
returnfunction(x, grad)
localn=#x
ifn~=#gradthen
error("value length must be equal to gradient length")
end
ifn~=#xdthen
error("value and gradient lengths must be as per initialization")
end
localval=0
fori=1,ndo
forj=1,ndoxd[j] =x[j] end
xd[i] =xd[i] +dn(0, 1)
localvd=dn(f(xd))
val=vd:val()
grad[i] =vd:adj()
end
returnval
end
end
return {
dn=dn,
derivativef=derivativef,
gradientf=gradientf,
}