Compare commits

...
9 Commits
Author SHA1 Message Date
Kevin P Murphy 784aa78f7c update jaxtyped decorator (#44)
* update jaxtyped decorator

* add newline character to pacify flake

* add precomit hooks

* add missing return statement

* replace typing_extensions>=4.2.0 with typing_extensions

* pin version range for typing_extensions

* set min version of typing-extensions but not max

* bump version number to 0.2.8
2022-11-13 22:25:28 -08:00
Patrick Kidger 3f877c0dbb Update array_types.py (#41) 2022-11-08 22:52:17 -08:00
Patrick Kidger 607f3c66b5 Silenced warning (#40) 2022-10-28 15:19:52 -07:00
Peter Roelants d3651ca70e NamedTuple example (#36) 2022-10-03 07:40:51 -07:00
Patrick Kidger d246e21281 Better import hook (#35) 2022-09-25 23:28:40 -07:00
Patrick Kidger 165065756f Static type-checking fix (#34) 2022-09-24 18:27:22 -07:00
ebrevdo dcd73e3431 Add support for e.g. jaxtyping.Float[Union[...], ...] in py3.8 (#31)
* Add support for e.g. jaxtyping.Float[Union[...], ...] in py3.8

Turns out that python3.8, Union lacks the __name__ attribute.  Use repr()
in these cases.

* Fix linter.

* Remove implicit cast to bool in favor of try/except.
2022-09-22 13:25:29 -07:00
Patrick Kidger f175c7f315 Fixed py.type not being packaged (#30) 2022-09-22 12:16:25 -07:00
Patrick Kidger da8300ec6c tidyness tweak (#28) 2022-09-20 15:16:52 -07:00
8 changed files with 100 additions and 36 deletions
+2 -2
View File
@@ -1,2 +1,2 @@
include LICENSE include jaxtyping/py.typed
prune tests prune test
+12 -8
View File
@@ -20,14 +20,18 @@
import typing import typing
if getattr(typing, "GENERATING_DOCUMENTATION", False): if typing.TYPE_CHECKING:
# type checkers don't know which branch below will be executed
class Array:
pass
Array.__module__ = "builtins"
else:
from jax.numpy import ndarray as Array from jax.numpy import ndarray as Array
else:
if getattr(typing, "GENERATING_DOCUMENTATION", False):
class Array:
pass
Array.__module__ = "builtins"
else:
from jax.numpy import ndarray as Array
from .array_types import ( from .array_types import (
AbstractArray, AbstractArray,
@@ -63,4 +67,4 @@ from .import_hook import install_import_hook
from .pytree_type import PyTree from .pytree_type import PyTree
__version__ = "0.2.4" __version__ = "0.2.8"
+16 -12
View File
@@ -150,26 +150,25 @@ class _MetaAbstractArray(type):
if cls.dtypes is not _any_dtype and dtype not in cls.dtypes: if cls.dtypes is not _any_dtype and dtype not in cls.dtypes:
return False return False
temp_memo = not hasattr(storage, "memo_stack") or len(storage.memo_stack) == 0 no_temp_memo = hasattr(storage, "memo_stack") and len(storage.memo_stack) != 0
if temp_memo: if no_temp_memo:
single_memo, variadic_memo, variadic_broadcast_memo = storage.memo_stack[-1]
# Make a copy so we don't mutate the original memo during the shape check.
single_memo = single_memo.copy()
variadic_memo = variadic_memo.copy()
variadic_broadcast_memo = variadic_broadcast_memo.copy()
else:
# `isinstance` happening outside any @jaxtyped decorators, e.g. at the # `isinstance` happening outside any @jaxtyped decorators, e.g. at the
# global scope. In this case just create a temporary memo, since we're not # global scope. In this case just create a temporary memo, since we're not
# going to be comparing against any stored values anyway. # going to be comparing against any stored values anyway.
single_memo = {} single_memo = {}
variadic_memo = {} variadic_memo = {}
variadic_broadcast_memo = {} variadic_broadcast_memo = {}
else:
single_memo, variadic_memo, variadic_broadcast_memo = storage.memo_stack[-1]
# Make a copy so we don't mutate the original memo during the shape check.
single_memo = single_memo.copy()
variadic_memo = variadic_memo.copy()
variadic_broadcast_memo = variadic_broadcast_memo.copy()
temp_memo = False
if cls._check_shape(obj, single_memo, variadic_memo, variadic_broadcast_memo): if cls._check_shape(obj, single_memo, variadic_memo, variadic_broadcast_memo):
# We update the memo every time we successfully pass a shape check # We update the memo every time we successfully pass a shape check
if not temp_memo: if no_temp_memo:
storage.memo_stack[-1] = ( storage.memo_stack[-1] = (
single_memo, single_memo,
variadic_memo, variadic_memo,
@@ -384,10 +383,15 @@ class _MetaAbstractDtype(type):
elem = compile(elem, "<string>", "eval") elem = compile(elem, "<string>", "eval")
elem = _SymbolicDim(elem, broadcastable) elem = _SymbolicDim(elem, broadcastable)
dims.append(elem) dims.append(elem)
# In python 3.8, e.g., typing.Union lacks `__name__`.
try:
type_str = array_type.__name__
except AttributeError:
type_str = repr(array_type)
if _array_name_format == "dtype_and_shape": if _array_name_format == "dtype_and_shape":
name = f"{cls.__name__}[{array_type.__name__}, '{dim_str}']" name = f"{cls.__name__}[{type_str}, '{dim_str}']"
elif _array_name_format == "array": elif _array_name_format == "array":
name = array_type.__name__ name = type_str
else: else:
raise ValueError(f"array_name_format {_array_name_format} not recognised") raise ValueError(f"array_name_format {_array_name_format} not recognised")
out = _MetaAbstractArray( out = _MetaAbstractArray(
+7 -1
View File
@@ -18,6 +18,7 @@
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import functools as ft import functools as ft
import inspect
import threading import threading
@@ -44,4 +45,9 @@ class _Jaxtyped:
def jaxtyped(fn): def jaxtyped(fn):
return ft.wraps(fn)(_Jaxtyped(fn)) if inspect.isclass(fn): # allow decorators on class definitions
init = jaxtyped(fn.__init__)
fn.__init__ = init
return fn
else:
return ft.wraps(fn)(_Jaxtyped(fn))
+25 -9
View File
@@ -65,7 +65,9 @@ def _call_with_frames_removed(f, *args, **kwargs):
def _optimized_cache_from_source(path, debug_override=None): def _optimized_cache_from_source(path, debug_override=None):
return cache_from_source(path, debug_override, optimization="jaxtyping") # Version 2: change the position of the `@jaxtyped` decorator, so need a
# different name to avoid hitting old __pycache__
return cache_from_source(path, debug_override, optimization="jaxtyping2")
class _JaxtypingTransformer(ast.NodeVisitor): class _JaxtypingTransformer(ast.NodeVisitor):
@@ -99,10 +101,16 @@ class _JaxtypingTransformer(ast.NodeVisitor):
has_annotated_args = any(arg for arg in node.args.args if arg.annotation) has_annotated_args = any(arg for arg in node.args.args if arg.annotation)
has_annotated_return = bool(node.returns) has_annotated_return = bool(node.returns)
if has_annotated_args or has_annotated_return: if has_annotated_args or has_annotated_return:
# Place at the start of the decorator list, in case a typechecking # Place at the end of the decorator list, as otherwise we wrap e.g.
# annotation has been manually applied; we need to be above that. # `jax.custom_{jvp,vjp}` and lose the ability to `defjvp` etc.
node.decorator_list.insert( #
0, # Note that the counter-argument here is that we'd like to place this
# at the start of the decorator list, in case a typechecking annotation
# has been manually applied, and we'd need to be above that. In this
# case we're just going to have to need to ask the user to remove their
# typechecking annotation (and let this decorator do it instead).
# It's more important we be compatible with normal JAX code.
node.decorator_list.append(
ast.Attribute( ast.Attribute(
ast.Name(id="jaxtyping", ctx=ast.Load()), "jaxtyped", ast.Load() ast.Name(id="jaxtyping", ctx=ast.Load()), "jaxtyped", ast.Load()
), ),
@@ -230,8 +238,16 @@ def install_import_hook(
- `typechecker`: the module and function of the typechecker you want to use, as a - `typechecker`: the module and function of the typechecker you want to use, as a
2-tuple of strings. For example `typechecker=("typeguard", "typechecked")` or 2-tuple of strings. For example `typechecker=("typeguard", "typechecked")` or
`typechecker=("beartype", "beartype")`. You may pass `typechecker=None` if you `typechecker=("beartype", "beartype")`. You may pass `typechecker=None` if you
do not want to automatically decorate with a typechecker as well; e.g. if you do not want to automatically decorate with a typechecker as well.
have a codebase that already has these decorators.
If the function already has any decorators on it, then both the `@jaxtyped` and the
typechecker decorators will go at the bottom of the decorator list, e.g.
```python
@some_other_decorator
@jaxtyped
@beartype.beartype
def foo(...): ...
```
**Returns:** **Returns:**
@@ -243,8 +259,8 @@ def install_import_hook(
```python ```python
# entry_point.py # entry_point.py
from jaxtyped import install_import_hook from jaxtyped import install_import_hook
install_import_hook("main", ("beartype", "beartype")) with install_import_hook("main", ("beartype", "beartype"))
import main import main
... # do whatever you're doing ... # do whatever you're doing
# main.py # main.py
+2 -2
View File
@@ -22,7 +22,7 @@ import typing
from typing import Generic, TYPE_CHECKING, TypeVar from typing import Generic, TYPE_CHECKING, TypeVar
from typing_extensions import Protocol from typing_extensions import Protocol
import jax import jax.tree_util as jtu
import typeguard import typeguard
@@ -83,7 +83,7 @@ class _MetaSubscriptPyTree(type):
else: else:
return True return True
leaves = jax.tree_leaves(obj, is_leaf=is_leaftype) leaves = jtu.tree_leaves(obj, is_leaf=is_leaftype)
return all(map(is_leaftype, leaves)) return all(map(is_leaftype, leaves))
+5 -1
View File
@@ -67,11 +67,14 @@ python_requires = "~=3.7"
# We use typeguard internally (in a fairly minimal way), but it's not required that # We use typeguard internally (in a fairly minimal way), but it's not required that
# end users make the same choice. # end users make the same choice.
# For typing_extensions, we choose versions that match
# https://github.com/explosion/confection/blob/main/setup.cfg#L33 used in colab
install_requires = [ install_requires = [
"jax>=0.3.4", "jax>=0.3.4",
"numpy>=1.20.0", "numpy>=1.20.0",
"typeguard>=2.13.3", "typeguard>=2.13.3",
"typing_extensions>=4.2.0", "typing_extensions>=3.7.4.1",
] ]
entry_points = dict(pytest11=["jaxtyping = jaxtyping.pytest_plugin"]) entry_points = dict(pytest11=["jaxtyping = jaxtyping.pytest_plugin"])
@@ -94,4 +97,5 @@ setuptools.setup(
install_requires=install_requires, install_requires=install_requires,
entry_points=entry_points, entry_points=entry_points,
packages=[name], packages=[name],
include_package_data=True,
) )
+31 -1
View File
@@ -17,7 +17,7 @@
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # 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. # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
from typing import Tuple, Union from typing import NamedTuple, Tuple, Union
import equinox as eqx import equinox as eqx
import jax import jax
@@ -155,3 +155,33 @@ def test_pytree_tuple(typecheck):
g([1, 1]) g([1, 1])
with pytest.raises(ParamError): with pytest.raises(ParamError):
g([(1, 1), "hi"]) g([(1, 1), "hi"])
def test_pytree_namedtuple(typecheck):
class CustomNamedTuple(NamedTuple):
x: Float[jnp.ndarray, "a b"]
y: Float[jnp.ndarray, "b c"]
class OtherCustomNamedTuple(NamedTuple):
x: Float[jnp.ndarray, "a b"]
y: Float[jnp.ndarray, "b c"]
@typecheck
def g(x: PyTree[CustomNamedTuple]):
...
g(
CustomNamedTuple(
x=jax.random.normal(jax.random.PRNGKey(42), (3, 2)),
y=jax.random.normal(jax.random.PRNGKey(420), (2, 5)),
)
)
with pytest.raises(ParamError):
g(object())
with pytest.raises(ParamError):
g(
OtherCustomNamedTuple(
x=jax.random.normal(jax.random.PRNGKey(42), (3, 2)),
y=jax.random.normal(jax.random.PRNGKey(420), (2, 5)),
)
)