Differentiation for Hackers
github.com
github.com
First I implemented simple forward mode AD in Python (with NumPy, handling gradients and Hessians so you could apply AD to find extrema of constrained variational problems, (to design constrained B-spline geometry for example... or construct equations of motion), then extended to handle interval analysis, which introduces a tiny bit of topology (fixed point theorems and such - provably find all solutions to nonlinear systems over some domain).
Then pick up declarative programming (unification) and revisit overloading to build up a mathematical expression tree for anything you have implemented. (In detail, overload math such that, for some object which is a mathematical combination of two other objects, store in the new object's memory some representation of the two original objects, and also the operation used to combine them. Remember to track your automatically generated-connectives! (all expressions are ternary - n-ary stuff get broken out into ternary stuff) )
Then starting at the final "node" of this mathematical tree, walk back down the tree to build whatever you want. (Reverse mode ad can be done this way, and is a good thing to try) I used it to automatically compile math down into logical rules for constraint programming. Much fun!
Now re-do it all in C++ but use overloading to build a math lib to support everything, or, use eigen, or some other expression template lib. (I'm not done with this.)
Ah, expression template libraries are another instance of "reverse mode style" expression tree computation. AKA the "interpreter pattern". Good fun here, but more involved I think.
In the author's packages, integers which label dimensions etc. have gradient `nothing`, but arrays which happen to contain integers do not signal anything:
julia> Zygote.gradient((x,d)->abs(sum(sin,fft(x,d))), [2 2; 0 0], 2)
(Complex{Float64}[-0.346356+0.0im 1.65364+0.0im; -2.0+0.0im 0.0+0.0im], nothing)AD is also on fairly shaky ground once you step outside what can be expressed in standard analytical calculus. For example it is fairly easy to express the same function in different ways and get derivatives that differ. A lot of work on semantics is needed.
Example?
I'd realized this was an issue with forward-mode autodiff, but hadn't thought about reverse-mode to realize it comes up there too.
In general, NaN is a placeholder for "all the derivatives you didn't know you needed in advance". I think the Dual Numbers shed light on this (see "Division": [https://en.wikipedia.org/wiki/Dual_number#Division]).
One could imagine lazily computing higher derivatives as needed for L'Hospital's Rule in either Forward or Reverse mode, however. For Forward Mode, I guess you'd replace your eager "Dual Number" pairs with lazy lists?
For reverse mode it seems you could do extra "passes" on the tape as needed... People who do this stuff for a living must know(?), but a quick Google doesn't turn up an answer for me...
It doesn't matter how many times you differentiate x^(1/3); you can not evaluate the result at zero. Which is funny, because you'd think you could differentiate x^3 and use the inverse function theorem. But there's that caveat about it not working when the derivative is zero.
I am now revisiting high school calculus and doubting my own sanity. Will post updates if/when I get my head right.
Program:
y = g(x) = x^3
z = f(y) = cuberoot(y)
Want: dz/dxReverse-mode autodiff:
// Forward pass
y = g(0) = 0^3 = 0 g'(0) = 3 x^2 = 0
z = f(0) = cuberoot(0) = 0 f'(0) = (1/3) / cuberoot(y^2) = (1/3)/0 = Inf
// Reverse pass
dz/dy = f'(0) = Inf
dz/dx = dz/dy * g'(0) = Inf * 0 = NaNOk,
f(x) = cuberoot(x^3)
f(0 + eps) = cuberoot((0 + eps)^3) = cuberoot(eps^3) = eps
e.g. value is 0 and the slope is 1.
>>> import autograd.numpy as np
>>> from autograd import grad
>>> def fn(x):
... return np.power(np.power(x, 3), 1/3)
...
>>> gradfn = grad(fn)
>>> gradfn(0.0)
/usr/local/lib/python3.6/dist-packages/autograd/numpy/numpy_vjps.py:59:RuntimeWarning: divide by zero encountered in double_scalars
lambda ans, x, y : unbroadcast_f(x, lambda g: g * y * x ** anp.where(y, y - 1, 1.)),
/usr/local/lib/python3.6/dist-packages/autograd/numpy/numpy_vjps.py:59: RuntimeWarning: invalid value encountered in double_scalars
lambda ans, x, y : unbroadcast_f(x, lambda g: g * y * x ** anp.where(y, y - 1, 1.)),
nan
… Damn. >>> import torch
>>> x = torch.tensor(0.0, requires_grad=True)
>>> y = ((x**3) ** (1/3))
>>> y.backward()
>>> x.grad
tensor(nan)
… Damn.> a complicated representation of) y=x.
The problem started as that. So no surprise.
Sure, we call that computer algebra. As soon as you start doing that, you aren't doing automatic differentiation, you are doing (at least in part) symbolic differentiation.
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
double f(const double x) {
return pow(x, 1000) / pow(x, 998);
}
int main(int argc, char* argv[]) {
if(argc != 2) {
fprintf(stderr, "Usage: %s x\n", argv[0]);
exit(1);
}
const double x = atof(argv[1]); // demo code without error checking
printf("x = %g, f(x) = %g\n", x, f(x));
exit(0);
}
compile with gcc -Wall -g -o test test.c -lm
and run it petschge@localhost:~$ ./test 0
x = 0, f(x) = -nan
petschge@localhost:~$ ./test 1
x = 1, f(x) = 1
petschge@localhost:~$ ./test 2
x = 2, f(x) = 4
The fun thing is, when you compile with gcc -Wall -O3 -ffast-math -g -o test2 test.c -lm
you actually get petschge@localhost:~$ ./test2 0
x = 0, f(x) = 0But autodiff doesn't replace symbolic differentiation. Consider the derivative of cuberoot(x^3). Autodiff struggles at x=0 because x^3 is flat (slope 0) and cuberoot is vertical (slope inf). And together, with autodiff, you get slope NaN.
If you wanted to try to fix that problem with autodiff, well first off it's likely not worth it because similar problems are inherent to autodiff, but you'll need an analytic understanding of what's going on.
If you want to claim that autodiff is a replacement for all our differentiation needs, then you should try to understand when it doesn't work.
The problem is really that there are a lot of ways the function can have infinite slope. The sqrt function also has infinite slope at 0.
Dividing by zero isn't where the NaN comes from.
"ZeroDivisionError: 0.0 cannot be raised to a negative power"
Is that satisfying? I do not claim anything more specific here. Sorry to be imprecise.
Analytical derivatives grow exponentially longer with the length of the expression. AD doesn't have this problem.
(I probably should not say this, but I will anyway: your comments regarding math and science always give me the distinct impression that you know the name of a lot of things without knowing much about the thing. You are frequently breathless about analog quantum computing, Lie algebras, Chu spaces, some universal concept of duality, but then you fail to respond with substantial arguments to people that try to temper the breathlessness. If you want to convince people of things, you should work on this.)
It does mean that. Pls see the overview paper http://jmlr.org/papers/volume18/17-468/17-468.pdf in particular section "2.1 AD Is Not Numerical Differentiation"
> substantial arguments to people that try to temper the breathlessness
Which arguments in particular?
> our comments regarding math and science always give me the distinct impression that you know the name of a lot of things without knowing much about the thing.
Ok be more specific, which ones do you care about? Maybe I don't always have time to answer everyone.
> some universal concept of duality
It's the concept of adjointness. And yes, it's very universal.
So no, I don't care about what you think, but I don't want to get banned.
Anyway, nice that you read the first version but still didn't respond to the other questions.
So no, understanding long division is not meaningless. It give you a starting point for a lot of other things.
https://blog.demofox.org/2014/12/30/dual-numbers-automatic-d...
And then you end up with adults who don't believe that the earth is round, that vaccines are low-risk and extremely beneficial and think that the existence of snow means that there is no climate change and that homeopathy and essential oils are a valid alternative to modern medicine, etc.