autoray.autoray¶
AUTORAY - backend agnostic array operations.
Copyright 2019-2026 Johnnie Gray
Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Attributes¶
Classes¶
Get an automatic dispatch (i.e. backend selection deferred to call time) |
|
A simple dispatch inferrer that always returns the same backend. Used |
|
A singleton object to use as a placeholder in a pytree, for |
|
Compose an |
|
Wrapper that possibly injects default dtype and device arguments, if not |
|
Mimics a namespace, optionally for a specific backend, device, and |
|
Stateful but deterministic random number generator for JAX following |
|
Stateful random number generator for TensorFlow following numpy's |
|
Stateful but deterministic random number generator for MLX following |
|
Draws from mlx's own shared random state, which |
Functions¶
|
Do function named |
|
This is the default backend dispatcher, used if no global backend has |
|
|
|
Return the universally set backend, if any. |
|
Set a default global backend. The argument |
|
Context manager for setting a default backend. The argument |
|
Register the name (and by default the module or submodule) of a custom |
|
Get the name of the library that defined the class of |
|
|
|
Infer which backend should be used for a function that takes multiple |
Remove all cache entries that depend on the backend of a class. |
|
Make a dispatcher function that possibly looks up default device and |
|
|
Infer the backend, device and dtype from like, with optional overrides |
|
Record whether |
|
Register a function that creates a new array, with dtype and possibly |
|
Private function to choose a backend based on function name and |
|
Choose a backend based on function name, arguments, and the |
|
|
|
Cached retrieval of correct function for backend, all the logic for |
|
Register an alias for a backend, i.e. if the backend alias is |
|
Register an alias for a module. |
|
Register an alias for a submodule location of a function. |
|
Register an alias for a function name. |
|
Register a custom wrapper for a function. The wrapper is called lazily |
|
Customize how a single function |
|
Is |
|
|
|
Is |
|
Register a new container type for use with |
The default function to determine if an object is a leaf. This simply |
|
|
|
|
Map |
|
|
|
Iterate over all leaves in |
|
|
|
Apply |
|
Flatten |
|
Unflatten |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Choose the namespace to supply to a composed function, given the |
|
Take a function consisting of multiple |
|
Get the shape of an array as a tuple of int. This should be preferred |
|
Get the number of dimensions of an array. This should be preferred to |
|
Get the size, or number of elements, of an array. This should be |
|
Array conjugate. |
|
Array transpose. |
|
Array Hermitian transpose. |
|
Array real part. |
|
Array imaginary part. |
|
Array reshaped. |
|
|
|
Turn string specifier |
|
|
Find string specifier |
|
|
Compute the minimal dtype sufficient for |
|
Cast array as type |
|
Get a numpy version of array |
Parse a composite string specifier like |
|
|
Whether string |
|
Move array |
|
Convert a numpy array (or array-like) |
|
Convert an array, or nested collection ("pytree") of arrays, to a |
|
|
|
Make a cholesky wrapper that translates upper to lower bool. |
Make a cholesky wrapper adding upper for backends that only compute |
|
Add ability to handle dtype keyword. |
|
|
Wrap a function to match the api of another according to a translation. |
|
|
|
|
|
|
Take a function with signature |
|
|
Register a new dispatcher, a function that takes the arguments and |
|
Try to infer backend from first argument passed to function. |
|
Dispatcher for functions where first argument is a sequence. |
|
Dispatcher for handling einsum. |
|
There are cases when we want to take into account both backends of two |
|
Use the generator's backend when given, or infer it from |
|
The lookup table to index for a rademacher sample: the two signs, or |
|
Draw from |
|
|
|
Generate an array of random samples. |
Cached |
|
|
Drop the cached lookups of |
Drop the cached function and submodule lookups of every live namespace, |
|
|
Get an automatic namespace object. |
|
|
|
Check a device string is valid for cupy, returning the gpu index, or |
|
|
|
|
|
|
|
|
|
Parse a device string like "cuda:0" into (platform, index). |
|
|
|
|
Warn one time only, since the message applies to every seedless call. |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Translate a device string like "cuda:0" to tensorflow form. |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Module Contents¶
- autoray.autoray.do(fn: str, *args, like=None, **kwargs)[source]¶
Do function named
fnon(*args, **kwargs), peforming single dispatch to retrievefnbased on whichever library defines the class of theargs[0], or thelikekeyword argument if specified.- Parameters:
fn (str) – Name of the function to do, e.g. ‘sum’ or ‘linalg.svd’.
args – Positional arguments to pass to the function.
like (str or array, optional) – Backend to use, either as an explicit backend name or an example array to infer the backend from. If not specified, the backend is inferred from the first argument, or from a globally set backend if any.
kwargs – Keyword arguments to pass to the function.
Examples
Works on numpy arrays:
>>> import numpy as np >>> x_np = np.random.uniform(size=[5]) >>> y_np = do('sqrt', x_np) >>> y_np array([0.32464973, 0.90379787, 0.85037325, 0.88729814, 0.46768083])
>>> type(y_np) numpy.ndarray
Works on cupy arrays:
>>> import cupy as cp >>> x_cp = cp.random.uniform(size=[5]) >>> y_cp = do('sqrt', x_cp) >>> y_cp array([0.44541656, 0.88713113, 0.92626237, 0.64080557, 0.69620767])
>>> type(y_cp) cupy.core.core.ndarray
Works on tensorflow arrays:
>>> import tensorflow as tf >>> x_tf = tf.random.uniform(shape=[5]) >>> y_tf = do('sqrt', x_tf) >>> y_tf <tf.Tensor 'Sqrt_1:0' shape=(5,) dtype=float32>
>>> type(y_tf) tensorflow.python.framework.ops.Tensor
You get the idea.
For functions that don’t dispatch on the first argument you can use the
likekeyword:>>> do('eye', 3, like=x_tf) <tf.Tensor: id=91, shape=(3, 3), dtype=float32>
- class autoray.autoray.DoFunc(fn: str)[source]¶
Get an automatic dispatch (i.e. backend selection deferred to call time) callable for function named
fn.Slightly faster equivalent to
functools.partial(do, fn).Examples
DoFunc objects have a fixed operation but can still be called on any type of array:
>>> sqrt = DoFunc('sqrt') >>> sqrt <DoFunc sqrt>
>>> import numpy as np >>> sqrt(np.random.uniform(size=[5])) array([0.32464973, 0.90379787, 0.85037325, 0.88729814, 0.46768083])
>>> import cupy as cp >>> sqrt(cp.random.uniform(size=[5])) array([0.44541656, 0.88713113, 0.92626237, 0.64080557, 0.69620767])
>>> import tensorflow as tf >>> sqrt(tf.random.uniform(shape=[5])) <tf.Tensor: shape=(5,), dtype=float32, numpy= array([0.3206495 , 0.8056399 , 0.5973012 , 0.13028008, 0.9820518 ], dtype=float32)>
- __slots__ = ('fn',)¶
- fn¶
- autoray.autoray._default_infer_from_sig(fn, *args, **kwargs)[source]¶
This is the default backend dispatcher, used if no global backend has been set. Hot swapping this function out as below avoids having to check manually for a global backend or worse, a thread aware global backend, on every call to
do.
- autoray.autoray._global_backend = None¶
- autoray.autoray._global_backends_threadaware¶
- autoray.autoray._inferrers_threadaware¶
- autoray.autoray._importing_thrid¶
- autoray.autoray._backend_lock¶
- class autoray.autoray.ConstantInferrer(backend)[source]¶
A simple dispatch inferrer that always returns the same backend. Used with set_backend to set a uniform constant backend for all calls.
- __slots__ = ('backend',)¶
- backend¶
- autoray.autoray.get_backend(get_globally='auto')[source]¶
Return the universally set backend, if any.
- Parameters:
get_globally ({"auto", False, True}, optional) –
Which backend to return:
True: return the globally set backend, if any.
False: return the backend set for the current thread, if any.
”auto”: return the globally set backend, if this thread is the thread that imported autoray. Otherwise return the backend set for the current thread, if any.
- Returns:
backend – The name of the backend, or None if no backend is set.
- Return type:
str or None
- autoray.autoray.set_backend(like, set_globally='auto')[source]¶
Set a default global backend. The argument
likecan be an explicit backend name or anarray.- Parameters:
like (str or array) – The backend to set. If an array, the backend of the array’s class will be set.
set_globally ({"auto", False, True}, optional) –
Whether to set the backend globally or for the current thread:
True: set the backend globally.
False: set the backend for the current thread.
”auto”: set the backend globally if this thread is the thread that imported autoray. Otherwise set the backend for the current thread.
Only one thread should ever call this function with
set_globally=True, (by default this is importing thread).
- autoray.autoray.backend_like(like, set_globally='auto')[source]¶
Context manager for setting a default backend. The argument
likecan be an explicit backend name or anarrayto infer it from.- Parameters:
like (str or array) – The backend to set. If an array, the backend of the array’s class will be set.
set_globally ({"auto", False, True}, optional) –
Whether to set the backend globally or for the current thread:
True: set the backend globally.
False: set the backend for the current thread.
”auto”: set the backend globally if this thread is the thread that imported autoray. Otherwise set the backend for the current thread.
Only one thread should ever call this function with
set_globally=True, (by default this is importing thread).
- autoray.autoray._CUSTOM_BACKENDS¶
- autoray.autoray.register_backend(cls, name)[source]¶
Register the name (and by default the module or submodule) of a custom array class.
- autoray.autoray.infer_backend(array)[source]¶
Get the name of the library that defined the class of
array- unlessarrayis directly a subclass ofnumpy.ndarray, in which case assumenumpyis the desired backend.
- autoray.autoray.multi_class_priorities¶
- autoray.autoray.infer_backend_multi(*arrays)[source]¶
Infer which backend should be used for a function that takes multiple arguments. This assigns a priority to each backend, and returns the backend with the highest priority. By default, the priority is:
builtins: -2numpy: -1other backends: 0
autoray.lazy: 1
I.e. when mixing with
numpy, other array libraries are preferred, when mixing withautoray.lazy,autoray.lazyis preferred. This has quite low overhead due to caching.
- autoray.autoray._backend_device_dtype_dispatchers¶
- autoray.autoray._invalidate_backend_inference_caches()[source]¶
Remove all cache entries that depend on the backend of a class.
- autoray.autoray._make_device_dtype_dispatch(like)[source]¶
Make a dispatcher function that possibly looks up default device and dtype if those are not given. Whether the dispatcher should look up those attributes is cached on like.__class__.
- autoray.autoray.infer_backend_device_dtype(like, device=None, dtype=None)[source]¶
Infer the backend, device and dtype from like, with optional overrides for device and dtype. The dispatcher is cached on like.__class__ to avoid repeated lookups of the same attributes for the same type of array.
- Parameters:
like (array-like or str or None) – The array to infer the backend, device and dtype from. If str, an explicit backend name. If None, the backend None is simply returned.
device (str or device_like, optional) – If given, an explicit device to use. If None, and like is an array with a device attribute, that is used.
dtype (str or dtype_like, optional) – If given, an explicit dtype to use. If None, and like is an array with a dtype attribute, that is used.
- Returns:
backend (str or None) – The inferred backend name, or None if like is None.
device (str or device_like or None) – The inferred device, or None if not given and not found on like.
dtype (str or dtype_like or None) – The inferred dtype, or None if not given and not found on like.
- autoray.autoray._CREATION_ROUTINES¶
- autoray.autoray._CREATION_INJECT¶
- autoray.autoray._register_creation_inject(backend, fn, inject_dtype, inject_device)[source]¶
Record whether
dtypeand/ordeviceshould be injected into the call to creation routinefnforbackend, based on thelikeargument. Seeregister_function.
- autoray.autoray.register_creation_routine(backend, fn, inject_dtype=True, inject_device=False)[source]¶
Register a function that creates a new array, with dtype and possibly device kwargs, that should be inferred from the like argument. This is not necessary for array creation routines that don’t accept either.
Deprecated since version 0.8.12: Prefer
register_function(backend, fn, inject_dtype=..., inject_device=...), which can register the location, name, wrapper and creation-injection behaviour of a function in a single call.- Parameters:
- autoray.autoray._choose_backend(fn, args, kwargs, like=None)[source]¶
Private function to choose a backend based on function name and signature, which passes args and kwargs by reference for performance and also to allow injection of dtype and device arguments for array creation routines.
- autoray.autoray.choose_backend(fn, *args, like=None, **kwargs)[source]¶
Choose a backend based on function name, arguments, and the
likekeyword argument. The default, iflikeis not specified, is to infer the backend from the function call, the default of which is simply to use the first argument, if no custom dispatcher is found. Otherwise the backend is chosen based on thelikeargument - which can be an explicit backend name or an arbitrary object.
- autoray.autoray._BACKEND_ALIASES¶
- autoray.autoray._MODULE_ALIASES¶
- autoray.autoray._SUBMODULE_ALIASES¶
- autoray.autoray._FUNC_ALIASES¶
- autoray.autoray._CUSTOM_WRAPPERS¶
- autoray.autoray._FUNCS¶
- autoray.autoray._COMPOSED_FUNCTION_GENERATORS¶
- autoray.autoray.get_lib_fn(backend, fn)[source]¶
Cached retrieval of correct function for backend, all the logic for finding the correct function only runs the first time.
- autoray.autoray.register_backend_alias(alias, backend)[source]¶
Register an alias for a backend, i.e. if the backend alias is inferred for an array, use functions from backend instead.
- autoray.autoray.register_submodule_alias(backend, fn, module)[source]¶
Register an alias for a submodule location of a function.
Deprecated since version 0.8.12: Prefer
register_function(backend, fn, module=module).
- autoray.autoray.register_func_alias(backend, fn, alias)[source]¶
Register an alias for a function name.
Deprecated since version 0.8.12: Prefer
register_function(backend, fn, alias=alias).
- autoray.autoray.register_custom_wrapper(backend, fn, wrapper=None)[source]¶
Register a custom wrapper for a function. The wrapper is called lazily so that no imports are done until the function is actually used.
Deprecated since version 0.8.12: Prefer
register_function(backend, fn, wrapper=wrapper), or as a decoratorregister_function(backend, fn, wrapper=True).
- autoray.autoray.register_function(backend, name, fn=None, *, wrap=False, module=None, alias=None, wrapper=None, inject_dtype=None, inject_device=None)[source]¶
Customize how a single function
nameis dispatched forbackend.This is the unified entry point for all function-level registration. It can set where the function lives (
module), what it is called in the backend (alias), a lazywrapperto apply on import, creation-routinedtype/deviceinjection, and/or a direct implementationfn.- Parameters:
backend (str) – The name of the backend to register the function for.
name (str) – Name of the function, e.g. ‘sum’ or ‘linalg.svd’.
fn (callable, optional) – A direct implementation to use. If not supplied, and no other keyword argument is given, this function can be used as a decorator with
backendandnameonly.wrap (bool, optional) – Whether to wrap the old function like
fn(old_fn)rather than directly supply the entire new function. This wrapper is eagerly called when registering, unlikewrapper.module (str, optional) – Register the submodule location of the function, for when it is found somewhere other than the expected
backendnamespace, e.g.'scipy.linalg'.alias (str, optional) – Register a different name that the function is called in the backend, e.g.
'absolute'for'abs'.wrapper (callable, optional) – Register a custom wrapper, called lazily as
wrapper(old_fn)the first time the function is imported, for when kwargs need translating or results modifying. Passwrapper=Truewithfn=Noneto use this as a decorator that captures the wrapper.inject_dtype (bool, optional) – Mark
nameas a creation routine that should have adtypeargument injected based on thelikeargument. Defaults toTruewheninject_deviceis given.inject_device (bool, optional) – Mark
nameas a creation routine that should have adeviceargument injected based on thelikeargument.
Examples
Register a relocated, renamed and wrapped function in a single call:
register_function( "paddle", "random.normal", module="paddle", alias="randn", wrapper=scale_normal_manually, )
Supply a direct implementation:
register_function("numpy", "complex", complex_add_re_im)
Use as a decorator for a direct implementation:
@register_function("torch", "to_numpy") def torch_to_numpy(x): return x.detach().cpu().numpy()
- autoray.autoray.is_array(x)[source]¶
Is
xan array-like object? This simply checks for ashapeattribute, thus 0-dimensional arrays are also considered arrays, but lists and tuples are not.See also
- autoray.autoray._IS_SCALAR_CACHE¶
- autoray.autoray.is_scalar(x)[source]¶
Is
xa scalar-like object? This checks ifxhas anndimattribute equal to 0. Ifxhas nondimattribute, it checks ifxis iterable - if it is not iterable, it is considered a scalar.See also
- autoray.autoray.TREE_MAP_REGISTRY¶
- autoray.autoray.TREE_APPLY_REGISTRY¶
- autoray.autoray.TREE_ITER_REGISTRY¶
- autoray.autoray.tree_register_container(cls, mapper, iterator, applier)[source]¶
Register a new container type for use with
tree_mapandtree_apply.- Parameters:
cls (type) – The container type to register.
mapper (callable) – A function that takes
f,treeandis_leafand returns a new tree of typeclswithfapplied to all leaves.applier (callable) – A function that takes
f,treeandis_leafand appliesfto all leaves intree.
- autoray.autoray.IS_CONTAINER_CACHE¶
- autoray.autoray.is_not_container(x)[source]¶
The default function to determine if an object is a leaf. This simply checks if the object is an instance of any of the registered container types.
- autoray.autoray.TREE_MAPPER_CACHE¶
- autoray.autoray.tree_map(f, tree, is_leaf=is_not_container)[source]¶
Map
fover all leaves intree, returning a new pytree.- Parameters:
f (callable) – A function to apply to all leaves in
tree.tree (pytree) – A nested sequence of tuples, lists, dicts and other objects.
is_leaf (callable) – A function to determine if an object is a leaf,
fis only applied to objects for whichis_leaf(x)returnsTrue.
- Return type:
pytree
- autoray.autoray.TREE_ITER_CACHE¶
- autoray.autoray.tree_iter(tree, is_leaf=is_not_container)[source]¶
Iterate over all leaves in
tree.- Parameters:
f (callable) – A function to apply to all leaves in
tree.tree (pytree) – A nested sequence of tuples, lists, dicts and other objects.
is_leaf (callable) – A function to determine if an object is a leaf,
fis only applied to objects for whichis_leaf(x)returnsTrue.
- autoray.autoray.TREE_APPLIER_CACHE¶
- autoray.autoray.tree_apply(f, tree, is_leaf=is_not_container)[source]¶
Apply
fto all leaves intree, no new pytree is built.- Parameters:
f (callable) – A function to apply to all leaves in
tree.tree (pytree) – A nested sequence of tuples, lists, dicts and other objects.
is_leaf (callable) – A function to determine if an object is a leaf,
fis only applied to objects for whichis_leaf(x)returnsTrue.
- class autoray.autoray.Leaf[source]¶
A singleton object to use as a placeholder in a pytree, for unflattening.
- __slots__ = ()¶
- autoray.autoray.LEAF¶
- autoray.autoray.tree_flatten(tree, is_leaf=is_not_container, get_ref=False)[source]¶
Flatten
treeinto a list of leaves.- Parameters:
tree (pytree) – A nested sequence of tuples, lists, dicts and other objects.
is_leaf (callable) – A function to determine if an object is a leaf, only objects for which
is_leaf(x)returnsTrueare returned in the flattened list.get_ref (bool) – If
True, a reference tree is also returned which can be used to reconstruct the original tree from a flattened list.
- Returns:
objs (list) – The flattened list of leaf objects.
(ref_tree) (pytree) – If
get_refisTrue, a reference tree, with leaves ofLeaf, is returned which can be used to reconstruct the original tree.
- autoray.autoray.tree_unflatten(objs, tree, is_leaf=is_leaf_placeholder)[source]¶
Unflatten
objsinto a pytree of the same structure astree.- Parameters:
objs (sequence) – A sequence of objects to be unflattened into a pytree.
tree (pytree) – A nested sequence of tuples, lists, dicts and other objects, the objs will be inserted into a new pytree of the same structure.
is_leaf (callable) – A function to determine if an object is a leaf, only objects for which
is_leaf(x)returnsTruewill have the next item fromobjsinserted. By default checks for theLeafobject inserted bytree_flatten(..., get_ref=True).
- Return type:
pytree
- autoray.autoray._choose_namespace(backend, args)[source]¶
Choose the namespace to supply to a composed function, given the already chosen
backendand the positionalargsof the call. The first argument supplies the dtype and device defaults if it belongs tobackend, otherwise the namespace has none.
- class autoray.autoray.Composed(fn, name=None)[source]¶
Compose an
autoray.dousing function. See the main wrappercompose.- _default_fn¶
- _name = None¶
- _supply_backend¶
- _supply_namespace¶
- autoray.autoray.compose(fn=None, *, name=None)[source]¶
Take a function consisting of multiple
autoray.docalls and compose it into a new, single, named function, registered withautoray.do.This creates a default implementation of this function for each new backend encountered without explicitly having to write each out, but also allows for specific implementations to be overridden for specific backends.
If the function takes a
backendargument, it will be supplied with the backend name, to save having to re-choose the backend. If it takes anamespaceargument, it will similarly be supplied with anAutoNamespace. Calling through a namespace supplies that namespace, otherwise it is taken from the first argument if that matches the backend, and has no dtype or device defaults if not.Specific implementations can be provided by calling the
registermethod of the composed function, or it can itself be used like a decorator:@compose def foo(x): ... @foo.register("numpy") @numba.njit def foo_numba(x): ...
Supply
nameto register the function under a name other than its own, which requires callingcomposefirst:@compose(name="linalg.qr") def qr(x): ...
- Parameters:
fn (callable, optional) – The function to compose, and its default implementation. Omitting it returns a decorator that takes it, which is how the second form above supplies
name.name (str, optional) – The name of the composed function. If not provided, the name of the function will be used.
- autoray.autoray.shape(x)[source]¶
Get the shape of an array as a tuple of int. This should be preferred to calling x.shape directly, as it:
Allows customization (e.g. for torch and aesara which return different types for shape - use @shape.register(backend) to customize the behavior from this default implementation).
Can be used on nested lists and tuples, without calling numpy.
- autoray.autoray.ndim(x)[source]¶
Get the number of dimensions of an array. This should be preferred to calling x.ndim, since not all backends implement that, and it can also be called on nested lists and tuples.
- Parameters:
x (array_like) – The array to get the number of dimensions of. It can be an arbitrary nested list or tuple of arrays and scalars.
- Returns:
ndim
- Return type:
- autoray.autoray.size(x)[source]¶
Get the size, or number of elements, of an array. This should be preferred to calling x.size, since not all backends implement that, and it can also be called on nested lists and tuples.
- Parameters:
x (array_like) – The array to get the size of. It can be an arbitrary nested list or tuple of arrays and scalars.
- Returns:
size
- Return type:
- autoray.autoray.to_backend_dtype(dtype_name, like)[source]¶
Turn string specifier
dtype_nameinto dtype of backendlike.
- autoray.autoray._BUILTIN_DTYPE_NAMES¶
- autoray.autoray._COMPLEX_DTYPES¶
- autoray.autoray._DOUBLE_DTYPES¶
- autoray.autoray._DTYPE_MAP¶
- autoray.autoray.astype(x, dtype_name, **kwargs)[source]¶
Cast array as type
dtype_name- triesx.astypefirst.
- autoray.autoray._DTYPE_MATCHER¶
- autoray.autoray._DEVICE_MATCHER¶
- autoray.autoray._parse_compound_backend_spec(spec)[source]¶
Parse a composite string specifier like
"torch-float32-cuda:0"into a(backend, dtype, device)tuple, each a string or None. Token order is not important: dtype and device tokens are recognized by pattern, and a single remaining token, if any, is taken as the backend.
- autoray.autoray._dtype_is_inexact(dtype_name)[source]¶
Whether string
dtype_nameis a floating point or complex dtype.
- autoray.autoray.to_device(x, device)[source]¶
Move array
xtodevice, returning it unchanged ifdeviceis None. A bare device type without an index, e.g."gpu"or"cuda", means ‘ensure on this type of device’: arrays already on such a device are not migrated between indices. The default implementation triesx.to(device), treating backends without any device concept as ‘cpu’.- Parameters:
x (array) – The array to move.
device (str or device-like or None) – The device to move to, e.g.
"cuda:0".
- Return type:
array
- autoray.autoray.from_numpy(x, dtype=None, device=None, backend=None)[source]¶
Convert a numpy array (or array-like)
xinto alikebackend array, directly with the givendtypeand on the givendevicewhere possible. It is registered as a creation routine, so iflikeis an example array, unspecifieddtypeanddevicedefault to matching it. The default implementation isasarraythento_device, but backends can register more direct routes, e.g. a singletorch.as_tensorcall.- Parameters:
x (array-like) – The numpy array (or nested iterable) to convert.
device (str or device-like, optional) – The target device, e.g.
"cuda:0".like (str or array, optional) – The target backend, as an explicit name, or an example array to also infer default
dtypeanddevicefrom. Handled by the dispatch layer.
- Return type:
array
- autoray.autoray.to(tree, like=None, *, backend=None, dtype=None, device=None)[source]¶
Convert an array, or nested collection (“pytree”) of arrays, to a target backend, dtype and/or device. All three can be specified together in a single string such as
"torch-float32-cuda:0", in any order, or explicitly via the keyword arguments, which take precedence. Unspecified properties are left unchanged, and non-array leaves are passed through untouched. Repeated references to the same input array are converted once and share the same output array. Note that, matchingtorch.nn.Module.tosemantics, only floating point and complex arrays are cast when adtypeis given, so that e.g. integer index arrays are preserved.- Parameters:
tree (array or pytree of arrays) – The array or nested collection (tuple, list, dict, or any registered container) of arrays to convert.
like (str or array, optional) – The conversion target. If a string, a dash separated specifier like
"backend-dtype-device", with each part optional. If an array, the backend, dtype and device to target are inferred from it.backend (str, optional) – Explicit target backend, taking precedence over
like.dtype (str or dtype, optional) – Explicit target dtype, taking precedence over
like. Only applied to floating point and complex arrays.device (str or device-like, optional) – Explicit target device, taking precedence over
like.
- Returns:
The converted array or collection, matching the structure of
tree.- Return type:
array or pytree of arrays
Examples
>>> import numpy as np >>> xs = {"a": np.random.rand(2, 3), "b": np.arange(3)} >>> ys = to(xs, "torch-float32") >>> ys["a"].dtype torch.float32 >>> ys["b"].dtype # integer arrays are not cast torch.int64
- autoray.autoray.cholesky_lower(fn)[source]¶
Make a cholesky wrapper that translates upper to lower bool.
- autoray.autoray.cholesky_manual_upper(fn)[source]¶
Make a cholesky wrapper adding upper for backends that only compute the lower factor.
- autoray.autoray.with_dtype_wrapper(fn)[source]¶
Add ability to handle dtype keyword. If not None, dtype should be specified as a string, otherwise conversion will happen regardless.
- autoray.autoray.translate_wrapper(fn, translator)[source]¶
Wrap a function to match the api of another according to a translation. The
translatorentries in the form of an ordered dict should have entries like:(desired_kwarg: (backend_kwarg, default_value))
with the order defining the args of the function.
- autoray.autoray.wrap_args_kwargs_from_raw(fn)[source]¶
Take a function with signature
(*args, **kwargs)and wrap it to accept a single tuple of args and a dict of kwargs.
- autoray.autoray.register_dispatch(fun, dispatcher, raw_signature=True)[source]¶
Register a new dispatcher, a function that takes the arguments and keyword arguments of a function and returns the backend to use, when the backend is not explicitly given.
This is useful in case the backend to be used by a function cannot be inferred from the first argument.
- Parameters:
fun (str) – The name of the function to register the dispatcher for.
dispatcher (callable) – The dispatcher function to use. This should take the arguments and keyword arguments of the function and return the backend to use.
raw_signature (bool, optional) – The
dispatcherhas signature(*args, **kwargs)ifTrue, otherwise it has signature(args, kwargs).
- autoray.autoray.default_dispatcher(args, kwargs)[source]¶
Try to infer backend from first argument passed to function.
- autoray.autoray._DISPATCHERS¶
- autoray.autoray.join_array_dispatcher(args, kwargs)[source]¶
Dispatcher for functions where first argument is a sequence.
- autoray.autoray.einsum_dispatcher(args, kwargs)[source]¶
Dispatcher for handling einsum.
einsum can be called with a str equation as the first argument, or with ‘interleaved’ inputs. This dispatcher handles both cases and also takes into account all arrays.
- autoray.autoray.binary_dispatcher(args, kwargs)[source]¶
There are cases when we want to take into account both backends of two arguments, e.g. a lazy variable and a constant array.
- autoray.autoray.random_array_dispatcher(shape, rng=None, **kwargs)[source]¶
Use the generator’s backend when given, or infer it from
shape.
- autoray.autoray._RANDOM_DISTS = ('normal', 'uniform', 'rademacher')¶
- autoray.autoray._COMPLEX_TO_REAL_DTYPE¶
- autoray.autoray._RADEMACHER_SIGNS¶
- autoray.autoray._RADEMACHER_ROOTS¶
- autoray.autoray._RADEMACHER_SAMPLERS¶
- autoray.autoray._RADEMACHER_SHARED¶
- autoray.autoray._get_rademacher_table(dtype_name, backend)[source]¶
The lookup table to index for a rademacher sample: the two signs, or the four roots of unity for a complex
dtype_name.
- autoray.autoray._sample_rademacher(rng, shape, dtype_name, device, backend)[source]¶
Draw from
{-1, +1}, or from the four roots of unity for a complexdtype_name. Both have modulus one and mean zero.
- autoray.autoray.random_array(shape, dist='normal', loc=0.0, scale=1.0, dtype=None, device=None, rng=None, backend=None)[source]¶
Generate an array of random samples.
- Parameters:
dist ({"normal", "uniform", "rademacher"}, optional) – Distribution to sample before applying
locandscale."rademacher"draws each entry from{-1, +1}, or from the four roots of unity for a complexdtype, with equal probability.loc (float or complex, optional) – Location applied after sampling.
scale (float or complex, optional) – Scale applied after sampling.
dtype (str or dtype_like, optional) – Output dtype, defaulting to that inferred from
like, orfloat64if there is none.device (str or device_like, optional) – Output device. Defaults to that inferred from
like.rng (int or random number generator, optional) –
Noneuses the backend’s shared random state where one is available. An integer makes a new generator for this call. A backend-specific generator uses and advances its own state, and also supplies the backend, so thatlikeis not needed. Each backend additionally accepts its own seed and state objects, such as a numpySeedSequenceorBitGenerator, or a jax key.
- Returns:
Random samples with
x = loc + scale * z. Before this transform, a complex normal or rademacherzhas total variance one, and a complex uniformzfills the unit square. A rademacherzhas modulus exactly one.- Return type:
array
- class autoray.autoray.InjectDtypeDevice(fn, device=None, dtype=None)[source]¶
Wrapper that possibly injects default dtype and device arguments, if not None, into the kwargs of function fn.
- __slots__ = ('_device', '_dtype', '_fn')¶
- _fn¶
- _device = None¶
- _dtype = None¶
- autoray.autoray._NAME_SPACE_SUBMODULES¶
- class autoray.autoray.AutoNamespace(like=None, device=None, dtype=None, submodule=None)[source]¶
Mimics a namespace, optionally for a specific backend, device, and dtype, caching the lookup of functions, and injecting default device and dtype arguments for certain creation routines.
- Parameters:
like (array_like, str, or None) – The backend to use, or an object to infer the backend from. If None, the default behavior is to use autoray.do and auto dispatch backend at function call time. If given, the functions are cached at first call.
device (str, optional) – The device to use for the backend. If None, it will be inferred from the like paramater is that is array-like or set to None.
dtype (str, optional) – The dtype to use for the backend. If None, it will be inferred from the like parameter if that is array-like or set to None.
submodule (str, optional) – This is used internally when nesting attribute lookups, e.g. xp.random.normal, xp.linalg.eigh.
- _submodule = None¶
- autoray.autoray._NAMESPACE_ATTRS = ('_backend', '_device', '_dtype', '_submodule')¶
- autoray.autoray._NAMESPACE_CACHE¶
- autoray.autoray._namespace_key_part(x)[source]¶
Cached
strof a device or dtype, which normalizes them for the namespace cache key. Cached becausenumpy.dtype.__str__is slow, and a composed function taking anamespacelooks one up on every call.
- autoray.autoray._reset_namespace(xp)[source]¶
Drop the cached lookups of
xpand of any submodule it made.
- autoray.autoray._reset_namespaces()[source]¶
Drop the cached function and submodule lookups of every live namespace, keeping the namespace objects themselves, so that a namespace held by a caller stays valid when functions are registered.
- autoray.autoray.get_namespace(like=None, device=None, dtype=None, submodule=None)[source]¶
Get an automatic namespace object.
If like is None, the namespace essentially provides an alternative syntax to do, dispatching each function at calltime, and allowing the backend and function implementations to be dynamically updated.
If like is supplied however, the backend is eagerly dispatched and functions are loaded and cached specifically for that backend. In this case, default device and dtype can also be specified for various array creation routines, or if like is an array, inferred from that.
- Parameters:
like (array-like, str or None, optional) – An array-like object to dispatch on, an explicit backend name, or None.
device (str or None, optional) – The device to use for array creation, or None to infer from like.
dtype (str or None, optional) – The data type to use for array creation, or None to infer from like.
- Returns:
An automatic namespace object.
- Return type:
- autoray.autoray.numpy¶
- autoray.autoray._builtin_dtype_lookup¶
- autoray.autoray._cupy_parse_device(device)[source]¶
Check a device string is valid for cupy, returning the gpu index, or None for a bare ‘gpu’ / ‘cuda’ (meaning any gpu).
- autoray.autoray._jax_parse_device(device)[source]¶
Parse a device string like “cuda:0” into (platform, index).
- autoray.autoray._warn_jax_generated_seed()[source]¶
Warn one time only, since the message applies to every seedless call.
- class autoray.autoray.JaxDefaultRNG(seed=None, **kwargs)[source]¶
Stateful but deterministic random number generator for JAX following numpy’s Generator API.
Create this generator inside a
jax.jitfunction from a seed or key passed to that function. A compiled function that captures a generator created outside it reuses the same values. Later use of that generator can also fail.seed=Nonewarns one time, because compilation chooses the generated seed once.- jax¶
- key¶
- autoray.autoray._JAX_DEFAULT_RNG = None¶
- class autoray.autoray.TensorflowDefaultRNG(seed=None, **kwargs)[source]¶
Stateful random number generator for TensorFlow following numpy’s Generator API, compatible with tf.function.
- tf¶
- autoray.autoray._tensorflow_translate_device(device)[source]¶
Translate a device string like “cuda:0” to tensorflow form.
- autoray.autoray._torch_reduce_translation = [('a', ('input',)), ('axis', ('dim',)), ('keepdims', ('keepdim',))]¶
- autoray.autoray.torch_scipy_linalg_solve_triangular(a, b, lower=False, unit_diagonal=False, **kwargs)[source]¶
- autoray.autoray._paddle_dtype_name_conversion¶
- class autoray.autoray.MlxDefaultRNG(seed=None, **kwargs)[source]¶
Stateful but deterministic random number generator for MLX following numpy’s Generator API.
- mx¶
- key¶
Bases:
MlxDefaultRNGDraws from mlx’s own shared random state, which
mx.random.seedsets, rather than from a key of its own.