quchip.utils.jax_utils¶
Helpers for tracer detection and array-namespace dispatch that quchip modules share.
JAX is a required dependency of quchip (see pyproject.toml).
Functions
|
Return the namespace of the array ( |
|
Return NumPy when all values are concrete, and |
|
Return |
|
Return |
|
Return |
|
Return a Python |
|
Raise |
|
Return |
- quchip.utils.jax_utils.contains_tracer(pytree)[source]¶
Return
Trueif pytree has ajax.core.Tracerleaf.It uses
jax.tree_util.tree_leaves(), so it traverses nested tuples, lists, dicts, and custom registered pytrees correctly.It covers all built-in JAX transforms, because
jit,vmap,grad,linearize,pmap, and their composition all make subclasses ofjax.core.Tracer.
- quchip.utils.jax_utils.raise_if(invalid, error, *values)[source]¶
Raise
error(*values)wheninvalidholds, also insidejax.jit.A traced check runs through
jax.experimental.io_callback(), which also survives callers that request only a gradient. The values reacherroras concrete arrays there. Insidejit, the exception reaches the caller as a JAX runtime error with the same message, so only an eager check raises the type thaterrorreturns.- Parameters:
invalid (bool or array_like) – Scalar condition, concrete or traced.
error (callable) – Returns the exception for the concrete
values.*values (array_like) – Diagnostic values for the exception.
- quchip.utils.jax_utils.array_namespace(array)[source]¶
Return the namespace of the array (
jax.numpyornumpy).It uses
__array_namespace__when available and falls back to NumPy.
- quchip.utils.jax_utils.is_jax_namespace(xp)[source]¶
Return
Trueif xp isjax.numpy(by module name).
- quchip.utils.jax_utils.is_jax_array(array)[source]¶
Return
Trueif array usesjax.numpyas its namespace.
- quchip.utils.jax_utils.select_array_module(prefer_jax)[source]¶
Return
jax.numpyif prefer_jax is true, else NumPy.
- quchip.utils.jax_utils.concrete_array_module(*values)[source]¶
Return NumPy when all values are concrete, and
jax.numpywhen a value is traced.Concrete arithmetic on the host compiles no XLA programs, whereas each eager JAX operation on a new shape compiles one.
- quchip.utils.jax_utils.maybe_concrete_scalar(value)[source]¶
Return a Python
floatif value is a concrete, real-valued 0-d scalar, elseNone.It examines a parameter that can be a JAX tracer. For a tracer, a non-scalar, or a complex or other payload that cannot convert to float, it returns
Noneinstead of afloator an error. Callers therefore treat complex-valued input like traced input, and skip the concrete validation check rather than run it on a lossy cast.