API reference¶
Compiling¶
parakeet.jit
¶
Compile a numerical Python function to native code on first call.
Use it bare (@jit) or with options (@jit(backend="metal")). The
function is specialised for each distinct combination of argument types;
every later call with the same types runs the cached native code.
Options (all default to the corresponding parakeet.config setting):
backend
"auto", "c", "multicore", "threads", "openmp",
"gcd", "metal"/"mps", "cuda" or "python".
bounds_check
Raise IndexError for out-of-range indices instead of crashing.
fusion
Fuse array expressions into single loops.
tiling
Tile matmul-shaped loops for cache locality.
parakeet.run(fn, *args, **kwargs)
¶
Compile fn (if needed) and call it: parakeet.run(f, x, y).
parakeet.specialize(fn, args, kwargs=None, backend=None)
¶
Compile fn for the types of the given arguments, without running it.
parakeet.typed_repr(fn, args, kwargs=None)
¶
The typed code Parakeet generates for fn applied to args, as text.
parakeet.Specialization
¶
One compiled version of a function for specific argument types.
operators
property
¶
The function as the frontend produced it: array operators (map, reduce)
over index spaces, before the passes of :mod:parakeet.transforms.pipeline.
ir
property
¶
The typed loop IR of this specialization (after every pass), as text.
source
property
¶
The generated C source.
kernels
property
¶
Source of every device kernel (empty for CPU backends).
signature
property
¶
Automatic differentiation¶
parakeet.grad(f, argnum=0)
¶
The gradient of the scalar-valued function f with respect to its
argument number argnum (or, for a tuple, to each of those arguments).
grad(f)(*args) takes the arguments of f and returns an array shaped
like the differentiated argument (a tuple of arrays for a tuple of
argument numbers; nested tuples of parameters give nested tuples of
gradients). Works inside compiled code and from plain Python.
parakeet.value_and_grad(f, argnum=0)
¶
Like :func:grad, but the new function returns (f(*args), gradient).
parakeet.jvp(fn, primals, tangents)
¶
Forward-mode Jacobian-vector product: returns (fn(*primals), d_fn).
primals and tangents are tuples of arguments matching fn (or single
values for unary functions). Works from plain Python and inside @par.jit
or other AD transforms with zero tape and O(1) extra memory.
parakeet.vjp(fn, *primals)
¶
General non-scalar reverse-mode AD: returns (primal_out, vjp_fn).
vjp_fn(cotangent) returns a tuple of input cotangents matching primals
for arbitrary scalar, array, tuple, record, or RaggedArray outputs.
parakeet.linearize(fn, *primals)
¶
Linearize fn at primals: returns (primal_out, lin_fn) where
lin_fn(*tangents) computes the directional derivative JVP(fn, primals, tangents).
parakeet.linear_transpose(linear_fn, *example_inputs)
¶
Return transpose_fn(cotangent) computing L^T(cotangent) for a linear function L.
parakeet.hvp(fn, primals, tangents, argnum=None)
¶
Exact Hessian-vector product H(fn)(primals) @ tangents via forward-over-reverse AD.
Runs in ~2x reverse-mode cost with zero O(N^2) Hessian allocation.
parakeet.jacfwd(fn, argnum=0)
¶
Forward-mode Jacobian of fn with respect to argument argnum.
parakeet.jacrev(fn, argnum=0)
¶
Reverse-mode Jacobian of fn with respect to argument argnum.
parakeet.hessian(fn, argnum=0)
¶
Exact Hessian of scalar-valued fn via forward-over-reverse AD.
parakeet.stop_gradient(el, x)
¶
Zero-copy gradient barrier: returns x with zero derivative under grad.
parakeet.checkpoint(fn)
¶
Drop forward intermediates of fn and recompute them during grad.
parakeet.custom_vjp(fn)
¶
Decorate fn so it can register a custom reverse-mode VJP with .defvjp(fwd, bwd).
parakeet.custom_jvp(fn)
¶
Decorate fn so it can register a custom forward-mode JVP with .defjvp(rule).
Backends, devices, and settings¶
parakeet.available_backends()
¶
Which backends work on this machine, with a reason for those that do not.
parakeet.target_profile(backend=None)
¶
Return the queried :class:~parakeet.target.TargetProfile for backend
(defaults to parakeet.config.backend).
parakeet.to_device(value, backend=None)
¶
Move a NumPy array (or nested tuple of arrays, such as model parameters and
optimizer state) onto a GPU backend as persistent :class:DeviceArrays.
When backend is None, uses parakeet.config.backend (or "gpu"
if the current backend is a CPU backend).
parakeet.to_host(value)
¶
Bring a :class:DeviceArray (or nested tuple of them) back to host NumPy arrays.
parakeet.DeviceArray
¶
An array resident on a GPU device (Metal or CUDA) across @jit calls.
Created with :func:parakeet.to_device or returned automatically by a
@jit function called with DeviceArray inputs. Passing a
DeviceArray into subsequent @jit calls on the same device avoids
redundant host-to-device uploads, and GPU-computed outputs are promoted
directly to DeviceArray without device-to-host downloads — keeping
weights, gradients, and optimizer state resident on the GPU throughout a
training loop.
Call :meth:numpy or :func:parakeet.to_host (or np.asarray(da)) to
bring the contents back to host memory.
sync_host()
¶
Bring the host backing array up to date if the device copy is newer.
ensure_device()
¶
Ensure a device buffer exists for this array, uploading once if needed.
numpy()
¶
Synchronize to host and return a NumPy ndarray copy.
copy()
¶
Return an independent copy resident on the same device.
parakeet.options(**settings)
¶
Temporarily override configuration settings.
with parakeet.options(backend="c", bounds_check=False): ... result = f(x)
parakeet.seed(value=None)
¶
Seed the random number generator used by np.random in compiled code.
Compiled code has its own counter-based generator (it must be usable from many threads and on GPUs), so streams differ from NumPy's, but are reproducible for a given seed and sequence of calls.
parakeet.clear_cache()
¶
Remove all compiled modules from the on-disk cache.
Structured folds and rewrite inspection¶
parakeet.show_rewrite(fn, *args, backend=None, blas=False, **opts)
¶
Compile-only algebraic rewrite inspection for fn on the types of args.
Works reliably on cold or warm specializations (including repeated calls and
calls after ordinary execution), supports plain functions,
@parakeet.jit functions, and grad / value_and_grad wrappers without
executing fn or mutating global compiler state.
parakeet.RewriteReport
dataclass
¶
Side-by-side summary of an algebraic rewrite performed by Parakeet.
parakeet.fold(el, lift, merge, x, init=None, *, axis=None, indexed=False, emit=None)
¶
Lift elements to scalar/fixed-vector tuple states and merge adjacent states in input order.
With no axis, lift each leading slice and return one state. With an axis,
fold the lanes along that axis and project each state with emit (which may
return a scalar, a fixed-size array, or a tuple/NamedTuple of them).
An indexed lift receives (value, index) with the index local to its lane.
A supplied seed is applied once on the left; an unseeded empty fold raises.
Diagnostics and verification¶
parakeet.find_broken_transform(fn, inputs, expected=None, print_transforms=True, print_functions=True)
¶
Name of the first optimization that makes fn(*inputs) differ from
expected (by default: what the function returns when run by Python).
Returns None if the compiled function is right with everything on, and
"frontend" if it is already wrong with every optimization off.
parakeet.verify(fn, phase='')
¶
Verify structural, scoping, typing, and ownership invariants of fn.
Returns fn so it can be used inline; raises :class:InternalError on any
violation.
Exceptions¶
parakeet.errors
¶
Exception hierarchy.
Compile-time problems are reported as :class:CompileError subclasses that
carry the location of the offending Python source, so the message points at the
user's code rather than at Parakeet internals. Runtime problems detected by
generated code (out-of-bounds indices, shape mismatches, ...) are re-raised as
the same built-in exception NumPy/Python would have raised.
ParakeetError
¶
Bases: Exception
Base class of every error raised by Parakeet itself.
CompileError
¶
Bases: ParakeetError
The function could not be compiled.
location is the innermost source position; call_chain lists the
call sites (outermost first) through which the failing code was inlined.
UnsupportedError
¶
TypeInferenceError
¶
StaticValueError
¶
BackendError
¶
Bases: ParakeetError
A backend failed to build or run generated code.
BackendUnavailable
¶
Bases: BackendError
The requested backend cannot run on this machine.
The message always says what is missing and how to get it.
CCompilerError
¶
InternalError
¶
Bases: ParakeetError
An invariant inside Parakeet was violated - please report it.
FallbackWarning
¶
Bases: UserWarning
A parallel loop could not run on the requested device and ran on the CPU.
Testing helpers¶
parakeet.testing
¶
Helpers for testing compiled functions against NumPy / pure Python.
check(fn, *args, backends=None, rtol=1e-06, **kwargs)
¶
Run fn in Python and compiled on every backend; results (including
their types) and any in-place changes to array arguments must agree.
same(actual, expected, rtol=1e-06)
¶
Strict comparison: values, shapes and types (Python vs NumPy scalar, dtype). Returns a description of the first difference, or None.
expect(fn, args, expected, msg=None, valid_types=None, backends=None)
¶
Assert that fn(*args) compiled by Parakeet equals expected on
every available CPU backend.
eq(x, y, rtol=1e-05, atol=1e-08)
¶
Structural, tolerance-based equality for scalars, arrays and tuples.