11from functools import wraps
22
3- import jax .experimental .host_callback as hcb
4- from jax import ShapeDtypeStruct , custom_vjp
3+ from jax import ShapeDtypeStruct
4+ from jax import __version__ as jax_version
5+ from jax import custom_vjp
6+ from packaging .version import Version
57from plum import Dispatcher , convert
68
9+ if Version (jax_version ) >= Version ("0.5" ):
10+ from jax .experimental import io_callback
11+
12+ # IO callbacks do not support JVP in JAX before `0.5`, so we emulate the call with
13+ # `host_callback`.
14+ else : # pragma: no cover
15+ from jax .experimental import host_callback
16+
17+ def io_callback (f , shapes , x ):
18+ return host_callback .call (f , x , result_shape = shapes )
19+
20+
721from ..custom import TensorDescription
822
923__all__ = ["jax_register" ]
@@ -30,13 +44,13 @@ def parse_inference_result(xs: tuple):
3044 return tuple (parse_inference_result (x ) for x in xs )
3145
3246
33- def _wrap_hcb (f , i_f ):
47+ def _wrap_cb (f , i_f ):
3448 @wraps (f )
3549 def f_wrapped (* args , ** kw_args ):
36- return hcb . call (
50+ return io_callback (
3751 lambda x : f (* x [0 ], ** x [1 ]),
38- arg = ( args , kw_args ),
39- result_shape = parse_inference_result ( i_f ( * args , ** kw_args ) ),
52+ parse_inference_result ( i_f ( * args , ** kw_args ) ),
53+ ( args , kw_args ),
4054 )
4155
4256 return f_wrapped
@@ -55,8 +69,8 @@ def jax_register(f, i_f, s_f, i_s_f):
5569 Returns:
5670 function: JAX function.
5771 """
58- f = _wrap_hcb (f , i_f )
59- s_f = _wrap_hcb (s_f , i_s_f )
72+ f = _wrap_cb (f , i_f )
73+ s_f = _wrap_cb (s_f , i_s_f )
6074
6175 f = custom_vjp (f )
6276
0 commit comments