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

Added argument check to all primitives. #2948

Merged
merged 2 commits into from
May 7, 2020
Merged
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
1 change: 1 addition & 0 deletions jax/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -1590,6 +1590,7 @@ def _check_args(args):
raise TypeError("Argument '{}' of type {} is not a valid JAX type"
.format(arg, type(arg)))

# TODO(necula): this duplicates code in core.valid_jaxtype
def _valid_jaxtype(arg):
try:
xla.abstractify(arg) # faster than core.get_aval
Expand Down
28 changes: 17 additions & 11 deletions jax/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from operator import attrgetter
from contextlib import contextmanager
from collections import namedtuple
from functools import total_ordering
from functools import total_ordering, reduce
import itertools as it
from weakref import ref
import threading
Expand Down Expand Up @@ -204,8 +204,6 @@ def __repr__(self):
return '{}'.format(self.name)

def bind(self, *args, **kwargs):
assert skip_checks or all(isinstance(arg, Tracer)
or valid_jaxtype(arg) for arg in args), args
top_trace = find_top_trace(args)
if top_trace is None:
return self.impl(*args, **kwargs)
Expand Down Expand Up @@ -623,14 +621,22 @@ def full_lower(val):
else:
return val

def find_top_trace(xs):
try:
top_trace = max((x._trace for x in xs if isinstance(x, Tracer)),
key=attrgetter('level'))
except ValueError:
return None
else:
return type(top_trace)(top_trace.master, cur_sublevel())
def find_top_trace(args) -> Optional[Tracer]:
"""Find the tracer with the highest-level, or None. """
def check_arg(top_so_far: Optional[Tracer], arg) -> Optional[Tracer]:
if isinstance(arg, Tracer):
return (top_so_far
if top_so_far and top_so_far.level >= arg._trace.level else arg._trace)
# Raises error here for bind on LAX primitives
if not valid_jaxtype(arg):
raise TypeError(f"Argument '{arg}' of type {type(arg)} is not a valid JAX type")
return top_so_far

top_trace = reduce(check_arg, args, None)
if top_trace is not None:
return type(top_trace)(top_trace.master, cur_sublevel()) # type: ignore[call-arg]
else:
return None

@contextmanager
def initial_style_staging():
Expand Down
6 changes: 5 additions & 1 deletion jax/lax/lax.py
Original file line number Diff line number Diff line change
Expand Up @@ -1199,7 +1199,7 @@ def top_k(operand: Array, k: int) -> Tuple[Array, Array]:
return top_k_p.bind(operand, k=k)

def tie_in(x: Array, y: Array) -> Array:
"""Gives ``y`` a fake data dependence on ``x``.
"""Returns the value of ``y`` but with a fake data dependence on ``x``.

When staging to XLA (e.g. running under jit or pmap), values that don't depend
on computation inputs are computed op-by-op, and folded into the XLA
Expand All @@ -1209,6 +1209,10 @@ def tie_in(x: Array, y: Array) -> Array:
When staging to XLA and ``x`` is already staged, then the result of ``tie_in``
is ``y``, but staged to XLA. Downstream use of the result will also be staged
to XLA.

For example, ``lax.sin(const)`` would be constant-folded if ``const`` is
a constant array, but ``lax.sin(lax.tie_in(x, const))``, will be staged to
XLA as long as ``x`` is staged to XLA.
"""
return tie_in_p.bind(x, y)

Expand Down
6 changes: 5 additions & 1 deletion tests/lax_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -2633,7 +2633,7 @@ def f2(x, y):
expected = onp.array(0.0)
self.assertAllClose(ans, expected, check_dtypes=False)

with self.assertRaises(TypeError if core.skip_checks else AssertionError):
with self.assertRaises(TypeError):
lax.stop_gradient(lambda x: x)

# TODO(mattjj): make this a more systematic test
Expand Down Expand Up @@ -3250,6 +3250,10 @@ def testTopK(self, shape, dtype, k, bdims, rng_factory):
# TODO Collapse
# TODO Scatter

def test_tie_in_error(self):
with self.assertRaisesRegex(TypeError,
".*tuple.* is not a valid JAX type"):
api.make_jaxpr(lambda x: lax.tie_in((x, x), 1))(1.)

if __name__ == '__main__':
absltest.main()