Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed error in grad_chooser (for e.g., max) when dtype is not numpy float64 #199

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion autograd/numpy/numpy_grads.py
Original file line number Diff line number Diff line change
Expand Up @@ -249,8 +249,12 @@ def grad_chooser(g, ans, vs, gvs, x, axis=None, keepdims=None):
"""Builds gradient of functions that choose a single item, such as min or max."""
g_repeated, _ = repeat_to_match_shape(g, vs, axis, keepdims)
argmax_locations = x == repeat_to_match_shape(ans, vs, axis, keepdims)[0]
if onp.isscalar(x.value):
dt = onp.array(x.value).dtype
else:
dt = x.dtype
return g_repeated * argmax_locations \
/ onp.sum(argmax_locations, axis=axis, keepdims=True)
/ onp.sum(argmax_locations, axis=axis, keepdims=True).astype(dt)

anp.max.defvjp(grad_chooser)
anp.min.defvjp(grad_chooser)
Expand Down
2 changes: 2 additions & 0 deletions autograd/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ def unary_nd(f, x, eps=EPS):
vs = vspace(x)
nd_grad = np.zeros(vs.size)
x_flat = vs.flatten(x)
if x_flat.dtype != np.float64:
nd_grad = nd_grad.astype(x_flat.dtype)
for d in range(vs.size):
dx = np.zeros(vs.size)
dx[d] = eps/2
Expand Down
10 changes: 10 additions & 0 deletions tests/test_numpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,16 @@ def fun(x): return to_scalar(np.max(x))
check_grads(fun, mat)
check_grads(d_fun, mat)

def test_max_dtype():
"""Tests that a dtype other than float64 does not throw an error
with the gradient of max.
"""
def fun(x): return to_scalar(np.max(x, 1))
d_fun = lambda x : to_scalar(grad(fun)(x))
mat = npr.randn(10, 11).astype(np.float32)
check_grads(fun, mat)
check_grads(d_fun, mat)

def test_max_axis():
def fun(x): return to_scalar(np.max(x, axis=1))
d_fun = lambda x : to_scalar(grad(fun)(x))
Expand Down