Skip to content

Instantly share code, notes, and snippets.

@gngdb
Created December 19, 2024 21:59
Show Gist options
  • Save gngdb/a6bdf48127dd5fc4773b95f283ee8d62 to your computer and use it in GitHub Desktop.
Save gngdb/a6bdf48127dd5fc4773b95f283ee8d62 to your computer and use it in GitHub Desktop.
Generated condensed version of https://github.com/mattjj/autodidact
"""
The MIT License (MIT)
Copyright (c) 2014 by the President and Fellows of Harvard University
Condensed version Copyright (c) 2024 by Gavia Gray
This condensed version is based on the original mattjj/autodidact implementation,
with assistance from Claude 3.5 Sonnet.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import numpy as _np
from collections import defaultdict
from contextlib import contextmanager
from itertools import count
# Core tracer functionality
class Box:
type_mappings = {}
types = set()
def __init__(self, value, trace_id, node):
self._value = value
self._node = node
self._trace_id = trace_id
@classmethod
def register(cls, value_type):
Box.types.add(cls)
Box.type_mappings[value_type] = cls
Box.type_mappings[cls] = cls
def new_box(value, trace_id, node):
try:
return Box.type_mappings[type(value)](value, trace_id, node)
except KeyError:
raise TypeError(f"Can't differentiate w.r.t. type {type(value)}")
class Node:
def __init__(self, value, fun, args, kwargs, parent_argnums, parents):
self.parents = parents
self.recipe = (fun, value, args, kwargs, parent_argnums)
def initialize_root(self):
self.parents = []
self.recipe = (lambda x: x, None, (), {}, [])
@classmethod
def new_root(cls):
root = cls.__new__(cls)
root.initialize_root()
return root
class TraceStack:
def __init__(self):
self.top = -1
@contextmanager
def new_trace(self):
self.top += 1
yield self.top
self.top -= 1
_trace_stack = TraceStack()
def trace(start_node, fun, x):
with _trace_stack.new_trace() as trace_id:
start_box = new_box(x, trace_id, start_node)
end_box = fun(start_box)
if isbox(end_box) and end_box._trace_id == start_box._trace_id:
return end_box._value, end_box._node
else:
return end_box, None
# Core VJP functionality
primitive_vjps = defaultdict(dict)
def backward_pass(g, end_node):
outgrads = {end_node: g}
for node in toposort(end_node):
outgrad = outgrads.pop(node)
fun, value, args, kwargs, argnums = node.recipe
for argnum, parent in zip(argnums, node.parents):
vjp = primitive_vjps[fun][argnum]
parent_grad = vjp(outgrad, value, *args, **kwargs)
outgrads[parent] = add_outgrads(outgrads.get(parent), parent_grad)
return outgrad
def add_outgrads(prev_g, g):
return g if prev_g is None else prev_g + g
def make_vjp(fun, x):
start_node = Node.new_root()
end_value, end_node = trace(start_node, fun, x)
if end_node is None:
def vjp(g): return _np.zeros_like(x)
else:
def vjp(g): return backward_pass(g, end_node)
return vjp, end_value
def grad(fun, argnum=0):
def gradfun(*args, **kwargs):
unary_fun = lambda x: fun(*subval(args, argnum, x), **kwargs)
vjp, ans = make_vjp(unary_fun, args[argnum])
return vjp(_np.ones_like(ans))
return gradfun
# Utilities
def subval(x, i, v):
x_ = list(x)
x_[i] = v
return tuple(x_)
def toposort(end_node):
child_counts = {}
stack = [end_node]
while stack:
node = stack.pop()
if node in child_counts:
child_counts[node] += 1
else:
child_counts[node] = 1
stack.extend(node.parents)
childless_nodes = [end_node]
while childless_nodes:
node = childless_nodes.pop()
yield node
for parent in node.parents:
if child_counts[parent] == 1:
childless_nodes.append(parent)
else:
child_counts[parent] -= 1
# NumPy wrapping functionality
def primitive(f_raw):
def f_wrapped(*args, **kwargs):
boxed_args, trace_id = find_top_boxed_args(args)
if boxed_args:
argvals = list(args)
for argnum, box in boxed_args:
argvals[argnum] = box._value
argvals = tuple(argvals)
parents = tuple(box._node for _, box in boxed_args)
argnums = tuple(argnum for argnum, _ in boxed_args)
ans = f_raw(*argvals, **kwargs)
node = Node(ans, f_wrapped, argvals, kwargs, argnums, parents)
return new_box(ans, trace_id, node)
else:
return f_raw(*args, **kwargs)
return f_wrapped
def find_top_boxed_args(args):
top_trace_id = -1
top_boxes = []
for argnum, arg in enumerate(args):
if isbox(arg):
if arg._trace_id > top_trace_id:
top_boxes = [(argnum, arg)]
top_trace_id = arg._trace_id
elif arg._trace_id == top_trace_id:
top_boxes.append((argnum, arg))
return top_boxes, top_trace_id
isbox = lambda x: type(x) in Box.types
getval = lambda x: getval(x._value) if isbox(x) else x
# NumPy box implementation
class ArrayBox(Box):
__array_priority__ = 100.0
def __init__(self, value, trace_id, node):
super().__init__(value, trace_id, node)
@property
def shape(self): return self._value.shape
@property
def ndim(self): return self._value.ndim
@property
def size(self): return self._value.size
@property
def dtype(self): return self._value.dtype
def __neg__(self): return np.negative(self)
def __add__(self, other): return np.add(self, other)
def __sub__(self, other): return np.subtract(self, other)
def __mul__(self, other): return np.multiply(self, other)
def __truediv__(self, other): return np.true_divide(self, other)
def __pow__(self, other): return np.power(self, other)
# Register array box
ArrayBox.register(_np.ndarray)
for type_ in [float, _np.float64, _np.float32]:
ArrayBox.register(type_)
# Create numpy namespace
class AutogradNumpy:
pass
np = AutogradNumpy()
# Define some basic VJPs
def unbroadcast(target, g):
while _np.ndim(g) > _np.ndim(target):
g = _np.sum(g, axis=0)
for axis, size in enumerate(_np.shape(target)):
if size == 1:
g = _np.sum(g, axis=axis, keepdims=True)
return g
def defvjp(fun, *vjps):
for argnum, vjp in zip(count(), vjps):
if vjp is not None:
primitive_vjps[fun][argnum] = vjp
# Define core numpy functions and their VJPs
basic_funcs = ['add', 'subtract', 'multiply', 'true_divide', 'power',
'negative', 'exp', 'log', 'sin', 'cos', 'tanh']
for name in basic_funcs:
setattr(np, name, primitive(getattr(_np, name)))
defvjp(np.add, lambda g, ans, x, y: unbroadcast(x, g),
lambda g, ans, x, y: unbroadcast(y, g))
defvjp(np.multiply, lambda g, ans, x, y: unbroadcast(x, y * g),
lambda g, ans, x, y: unbroadcast(y, x * g))
defvjp(np.subtract, lambda g, ans, x, y: unbroadcast(x, g),
lambda g, ans, x, y: unbroadcast(y, -g))
defvjp(np.true_divide, lambda g, ans, x, y: unbroadcast(x, g / y),
lambda g, ans, x, y: unbroadcast(y, -g * x / y**2))
defvjp(np.power, lambda g, ans, x, y: unbroadcast(x, g * y * x ** (y - 1)),
lambda g, ans, x, y: unbroadcast(y, g * _np.log(x) * x ** y))
defvjp(np.negative, lambda g, ans, x: -g)
defvjp(np.exp, lambda g, ans, x: ans * g)
defvjp(np.log, lambda g, ans, x: g / x)
defvjp(np.sin, lambda g, ans, x: g * _np.cos(x))
defvjp(np.cos, lambda g, ans, x: -g * _np.sin(x))
defvjp(np.tanh, lambda g, ans, x: g / _np.cosh(x) ** 2)
# Testing utilities
def finite_difference(f, x, eps=1e-8):
"""Compute gradient using finite difference."""
return (f(x + eps) - f(x - eps)) / (2 * eps)
def check_gradient(f, x, tol=1e-4):
"""Compare autograd gradient with finite difference."""
grad_f = grad(f)
auto_grad = grad_f(x)
num_grad = finite_difference(f, x)
diff = abs(auto_grad - num_grad)
print(f"x = {x}")
print(f"Autograd gradient: {auto_grad}")
print(f"Numeric gradient: {num_grad}")
print(f"Difference: {diff}")
assert diff < tol, f"Gradient check failed! Difference: {diff}"
print("Gradient check passed!")
# Example usage and testing:
if __name__ == "__main__":
def example_fun(x):
return np.sin(x) * np.exp(x)
x = 2.0
check_gradient(example_fun, x)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment