Python API reference¶
Generated from the docstrings of the public modules. For explanations and examples, start with Concepts; the numerical rules are in Numerics.
kernox.runtime
¶
kernox runtime: compile, input validation, backend registry.
All validation (names, shapes, dtypes, device, contiguity, K, gradients)
happens before any native launch. No fallback: a missing backend or an
unsupported operation raises an explicit error. The "oracle" backend
(blockwise Torch reference) is only used when explicitly requested;
backend="auto" never selects the oracle.
Registry: a native backend is a kernox.backends.<name> module that
exposes get_backend() -> Backend (loaded lazily), or an object
registered with :func:register_backend.
Reduction
¶
Compiled reduction (callable). Call: run(x=..., y=..., sigma=0.7).
Returns: a tensor (SUM, COUNT, MIN, MAX, ARG, KMIN, ARGKMIN, LOGSUMEXP,
SUMSOFTMAXWEIGHT) or the tuple (values, indices) for KMIN_ARGKMIN,
MIN_ARGMIN and MAX_ARGMAX.
tuning_decisions
property
¶
Measured or loaded decisions (outside estimate), per device and size class.
compiled(device, m=1, n=1)
¶
Compiled object (estimate variant) for device and sizes M, N.
validate(kwargs)
¶
Returns (tensors, device, M, N, B) or raises ValidationError.
B: broadcast batch shape, None without batch.
linear_operator(var, /, **inputs)
¶
:class:~kernox.linalg.LinearOperator v ↦ self(**inputs, var=v) (SUM linear in var).
solve(var, rhs, /, *, alpha=1e-10, eps=1e-06, maxiter=None, x0=None, inputs=None, **kwargs)
¶
Solves (alpha·I + K) var = rhs by conjugate gradient, with K = self viewed as linear in var.
The other inputs are passed by keyword (or inputs={...} if a
name conflicts with alpha, eps, maxiter, x0).
See :meth:kernox.linalg.LinearOperator.solve.
with_ranges(ranges, *, validate=False)
¶
Call restricted to the blocks of ranges (:class:kernox.Ranges).
run.with_ranges(r)(**inputs). validate=True checks the values
(bounds, overlaps; one host synchronization per call).
RangedReduction
¶
Reduction restricted by block-sparse ranges (run.with_ranges(r)).
Triplets in the plan orientation: fwd for the forward pass,
bwd (transposed, possibly None) for the j-side gradients.
register_backend(name, factory, *, replace=False)
¶
Registers factory() -> Backend under name.
get_backend(name)
¶
(Cached) instance of backend name; explicit error if missing.
auto_backend_name(device)
¶
Native backend for a Torch device: cuda (NVIDIA), hip (ROCm), sycl (XPU).
compile(expr, *, dtype, backend='auto', acc_dtype=None, tuning='estimate', fp_contract=None, sum_scheme=None, fast_math=None)
¶
Compiles a frontend reduction (or a :class:Plan) into a callable.
dtype is mandatory ("float16", "float32" or "float64"): no
implicit precision. backend: "auto" (device of the tensors:
cuda/hip/sycl), a native name, or "oracle" (explicit reference).
tuning: "estimate" (default, no measurement), "wisdom_only",
"measure" or "patient" (see :mod:kernox.tuning).
fp_contract: True by default, FMA contraction
allowed within an expression; False forbids it on all
backends (bit-for-bit reproducibility; a backend that cannot
guarantee it raises :class:UnsupportedError). Part of the plan key.
sum_scheme: "direct" (default), "block" or
"kahan" (Neumaier) for SUM, LOGSUMEXP and SUMSOFTMAXWEIGHT; ignored by
the other reductions. A backend that does not implement it raises
:class:UnsupportedError, never a fallback to "direct".
fast_math: False by default (IEEE); True allows
approximate exp/log (CUDA FP32: ex2.approx/lg2.approx, like PyKeOps
use_fast_math). Part of the plan key; a backend that does not
implement it raises :class:UnsupportedError. The oracle stays IEEE.
kernox.expr
¶
kernox frontend: i/j variables, parameters, formulas.
A :class:Formula is a vector (dimension dim) of scalar symox
expressions; the components of variables are real symox.Symbol objects.
No string is parsed: Python operators directly build the symox DAG. See
the Concepts and Formula operations pages of the documentation.
Formula
¶
Vector of scalar symox expressions and the variables it depends on.
components: tuple of symox expressions; dim: length;
variables: {name: (role, dim)}.
sum(*args, **kwargs)
¶
Sum of the components (scalar). To reduce an axis: sum_over.
sum_over(axis)
¶
Sum over the axis axis; a boolean formula gives a count (COUNT).
min_argmin(*, over)
¶
MIN and ARGMIN in a single pass (PyKeOps min_argmin): (values, indices).
max_argmax(*, over)
¶
MAX and ARGMAX in a single pass (PyKeOps max_argmax): (values, indices).
logsumexp(*, over, weight=None)
¶
log Σ exp f over the axis over, per component (PyKeOps logsumexp), output (M, D).
weight=g (PyKeOps logsumexp(weight=g)): log Σ exp(f) g_e with
scalar f and g of dimension E, output (M, E).
sumsoftmaxweight(g, *, over)
¶
Σ softmax(f) · g over the axis over (PyKeOps sumsoftmaxweight), output (M, E).
self: scalar score f; g: weights of dimension E >= 1.
ReductionExpr
¶
Pairwise reduction of a formula (terminal node, compiled with :func:kernox.compile).
to_plan(dtype, *, acc_dtype=None, fp_contract=True, sum_scheme=None, fast_math=False)
¶
Normalized plan (reduction over j): if over='i', the i/j roles are swapped.
constant(value, *, boolean=False)
¶
Convert a Python constant into an exact symox number.
bool:symox.true/falsein a boolean context, otherwise integer 0/1 (Python semantics);int→ exactInteger(arbitrary size);float→ 53-bit precisionFloatcarrying exactly the binary64 value of the Pythonfloat(no FP32 rounding at this stage);inf→oo,nan→nan;fractions.Fraction→ exactRational;- NumPy integer/floating scalars: like
int/float(annp.float32is converted exactly to binary64); - symox numbers (
Rational(1, 3),pi,E...): kept exact.
Rounding to the plan's dtype only happens when the plan is built
(:func:kernox.builder.convert_constants).
Vi(name, dim=1, *, complex=False)
¶
Variable indexed by i: tensor (M, dim) passed under the name name.
complex=True: :class:~kernox.complex.ComplexFormula; complex tensor
(M, dim) or its interleaved real view (M, 2·dim).
Vj(name, dim=1, *, complex=False)
¶
Variable indexed by j: tensor (N, dim) passed under the name name (complex: see Vi).
Param(name, dim=1, *, complex=False)
¶
Parameter constant over the pairs: tensor (dim,) or Python scalar if dim=1.
abs(x)
¶
Component-wise absolute value (modulus for a complex formula).
rsqrt(x)
¶
Exact 1/sqrt(x) (no approximate rsqrt instruction).
minimum(a, b)
¶
Component-wise minimum (symox Min).
where(cond, a, b)
¶
a if cond else b, component-wise (Piecewise).
The result is always that of the active branch: an invalid value in the
inactive branch (sqrt(-1), log(0), 1/0) affects neither the
value nor the gradient.
cat(*formulas)
¶
Concatenation of the components.
kernox.ops
¶
Formula operations for PyKeOps parity (keopscore formulas/maths).
Each operation reproduces the exact semantics of keopscore (reference
sources: keopscore/formulas/maths/*.py and
keopscore/utils/math_functions.py), expressed with symox primitives
(Piecewise, floor, comparisons, arithmetic): no codegen extension,
and the same DAG is printed by the three backends, the Torch oracle and the
NumPy reference. Deliberate deviations (behaviors left undefined by
keopscore) are flagged in each docstring and in the
"Coming from PyKeOps" page of the documentation.
Memory layout of "matrix" vectors: row-major, like keopscore
(C_CONTIGUOUS 1).
relu(x)
¶
(x < 0) ? 0 : x (keopscore ReLU; NaN → NaN).
step(x)
¶
(x < 0) ? 0 : 1 (keopscore Step; NaN → 1, like keopscore).
sinxdivx(x)
¶
x ? sin(x)/x : 1 (keopscore SinXDivX).
sinc(x)
¶
sin(πx)/(πx), i.e. sinxdivx(π·x) (PyKeOps LazyTensor.sinc).
xlogx(x)
¶
x ? x·log(x) : 0 (keopscore XLogX).
inv(x)
¶
1/x (keopscore Inv).
round(x, d=0)
¶
Rounding to d decimal places (keopscore Round): round(x·10^d)/10^d.
d = 0: C round(x) (half away from zero). The factor 10^d
is an exact constant; the final division is rounded once.
mod(x, modulus, offset=0)
¶
x − n·floor((x − d)/n) (keopscore Mod, n = modulus, d = offset).
clamp(x, lo, hi)
¶
Alias of :func:kernox.clamp (min(max(x, lo), hi)).
keopscore writes (x < a) ? a : ((x > b) ? b : x); the two coincide
except for NaN (keopscore propagates NaN, for min/max it depends on the backend).
The deviation is listed in the "Coming from PyKeOps" documentation page.
clampint(x, lo, hi)
¶
clamp with fixed integer bounds (keopscore ClampInt).
ifelse(x, a, b)
¶
(x >= 0) ? a : b (keopscore IfElse).
normalize(x)
¶
x · rsqrt(|x|²) with rsqrt(0) = 0 (keopscore Normalize: zero vector → 0).
sqdist(x, y)
¶
|x − y|² (keopscore SqDist).
weightedsqnorm(x, s)
¶
Norm of x weighted by s (PyKeOps x.weightedsqnorm(s)).
dim(s) = 1: s·|x|²; dim(s) = D: Σ s_k x_k²;
dim(s) = D²: Σ_{kl} s_{kl} x_k x_l (row-major matrix). For
D = 1, the isotropic case applies (like keopscore).
weightedsqdist(x, y, s)
¶
weightedsqnorm(x − y, s) (PyKeOps x.weightedsqdist(y, s)).
one_hot(x, D)
¶
Vector of dimension D equal to 1 at (int)(x + 0.5) (keopscore OneHot).
keopscore computes x + .5 in double then truncates toward zero: the
component k ≥ 1 is 1 if k − 1/2 ≤ x < k + 1/2, the component 0 if
−3/2 < x < 1/2 (exact comparisons, without rounding x + 0.5).
Outside [0, D) (undefined behavior in keopscore) and NaN: zero vector.
elem(x, i)
¶
Component i (keopscore Elem), 0 ≤ i < dim.
extract(x, i, d)
¶
Components i … i+d−1 (keopscore Extract).
matvecmult(A, v)
¶
(A v)_i = Σ_k A[i·m + k] v_k with A row-major (n, m), m = dim(v).
vecmatmult(v, A)
¶
(v A)_i = Σ_k v_k A[k·n + i] with A row-major (m, n), m = dim(v).
tensorprod(a, b)
¶
Tensor product out[k·dim(b) + l] = a_k b_l (keopscore TensorProd).
tensordot(a, b, dimfa, dimfb, contfa, contfb, permute=None)
¶
Contracted tensor product (keopscore TensorDot, PyKeOps keops_tensordot).
a (resp. b) viewed as a row-major tensor of shape dimfa
(dimfb); contraction of the axes contfa with contfb (like
numpy.tensordot), remaining axes of a then of b. permute:
permutation in the keopscore sense, the output is the tensor transposed by
argsort(permute) then flattened row-major.
kron(a, b, dimfa, dimfb)
¶
Kronecker product over the inner dimensions (keopscore Kron, numpy.kron).
bspline(knots, x, k=0)
¶
B-spline functions of order k on the knots knots, evaluated at scalar x.
keopscore BSpline (in-place De Boor algorithm, same order of
operations): output of dimension dim(knots) − k − 1. Order 0:
indicator t_j ≤ x < t_{j+1}; ratios ω = (x − t_i)/(t_{i+k} − t_i)
if t_i < t_{i+k}, 0 otherwise. Differentiable here with respect to x and to the
knots (keopscore is not).
softdtw_sqdist(x, y, gamma)
¶
Soft-DTW between the series x (dim n) and y (dim m), cost (x_i − y_j)².
keopscore SoftDTW_SqDist: dynamic programming r(i, j) with
r(0,0) = d², cumulative borders, then
r = d² + (μ − γ·log(e^{(μ−r(i−1,j−1))/γ} + e^{(μ−r(i−1,j))/γ} + e^{(μ−r(i,j−1))/γ})),
μ = min(r(i−1,j−1), r(i,j−1), r(i−1,j)); output r(n−1, m−1).
The recurrence is unrolled symbolically (DAG of size O(n·m), shared
through CSE): the gradient (with respect to x, y and γ) is the symbolic
derivative of this DAG. keopscore codes a loop and a dedicated gradient, and
refuses the derivative with respect to γ.
grad(f, v, e)
¶
(∂f/∂v)ᵀ e (keopscore Grad(f, v, e)): dimension of v, e of dimension of f.
Symbolic derivative (rules of :mod:kernox.autograd: Heaviside of
min/max → 1/2 at ties, where differentiated branch by branch).
diff(f, v, u)
¶
(∂f/∂v) u (keopscore Diff(f, v, u), differential applied to u): dimension of f.
grad_matrix(f, v)
¶
Matrix ∂f_k/∂v_c flattened as k·dim(v) + c (keopscore GradMatrix).
divergence(f, v)
¶
Σ_c ∂f_c/∂v_c (keopscore Divergence); dim(f) = dim(v).
laplacian(f, v)
¶
Σ_c ∂²f/∂v_c² (keopscore Laplacian); scalar f.
trace_operator(f, v)
¶
Trace of the linear map v ↦ f(v) (keopscore TraceOperator): Σ_c ∂f_c/∂v_c.
keopscore requires f to be linear in v; the trace of the differential is
then the trace of the map, and that is what is computed here for any f.
factorize(f, g)
¶
f.factorize(g) (keopscore Factorize): evaluation hint, with no semantic effect.
keopscore evaluates g once into a temporary then f; here code
generation always applies symox's CSE (per region in the
presence of where, see codegen.pair._region_cse), which already
factors out any repeated subexpression: the formula is returned unchanged.
auto_factorize(f)
¶
f.auto_factorize() (keopscore AutoFactorize): identity, CSE always applied.
kernox.complex
¶
Complex formulas (parity with PyKeOps ComplexLazyTensor, keopscore formulas/complex).
keopscore representation: a complex formula of dimension D is a real
:class:~kernox.expr.Formula of dimension 2D, with interleaved
components (re_0, im_0, re_1, im_1, …). Each operation is the
keopscore definition re-expressed with real symox primitives (no complex
type in the engine nor in the backends):
Real2Complex(x) = (x, 0),Imag2Complex(x) = (0, x),ComplexExp1j(x) = (cos x, sin x);ComplexReal,ComplexImag,Conj = (re, −im),ComplexSquareAbs = re² + im²,ComplexAbs = sqrt(re² + im²),ComplexAngle = atan2(im, re),ComplexExp = (exp(re)·cos(im), exp(re)·sin(im));ComplexAdd,ComplexSubtract,ComplexMult = (ac − bd, ad + bc),ComplexRealScal(real of dimension 1 × complex),ComplexDivide(f, g) = Real2Complex(1/|g|²) · (f · conj(g)),ComplexSum(sum of the complex components);- broadcasting of a complex dimension 1 to D, like
VectorizedComplexScalarOp.
Inputs: Vi(name, D, complex=True) (likewise Vj, Param) expects a
complex tensor (…, L, D) (complex64 in FP32, complex128 in FP64)
or its interleaved real view (…, L, 2D). Reduction: z.sum_over(ax) returns
a complex tensor (…, M, D). Gradients go through
torch.view_as_real (Torch convention for complex numbers).
ComplexDim
¶
Bases: int
Real dimension (2D) of a complex variable: marker carried by Formula._vars.
ComplexFormula
¶
Complex formula: interleaved real :class:Formula of dimension 2·dim.
formula
property
¶
Interleaved real formula (re_0, im_0, …).
square_abs()
¶
re² + im² (keopscore ComplexSquareAbs).
abs()
¶
Modulus sqrt(re² + im²) (keopscore ComplexAbs, without hypot).
angle()
¶
Argument atan2(im, re) (keopscore ComplexAngle).
exp()
¶
exp(re)·(cos im, sin im) (keopscore ComplexExp).
sum(*args, **kwargs)
¶
Sum of the complex components (keopscore ComplexSum), dimension 1.
factorize(g)
¶
Identity (CSE always applied), see :func:kernox.ops.factorize.
ComplexReductionExpr
¶
Bases: ReductionExpr
SUM of a complex formula: real plan of dimension 2D, output returned as complex.
complex_args(variables)
¶
Names of the complex variables of a dictionary {name: (role, dim)}.
real2complex(x)
¶
(x, 0) component-wise (keopscore Real2Complex).
imag2complex(x)
¶
(0, x) (keopscore Imag2Complex).
exp1j(x)
¶
(cos x, sin x) (keopscore ComplexExp1j).
complex_formula(re, im)
¶
re + i·im from two real formulas of the same dimension (or broadcast).
complex_input(name, value, dim2)
¶
Complex tensor (…, L, D) → interleaved real view (…, L, 2D) (differentiable).
complex_output(out)
¶
Interleaved real output (…, M, 2D) → complex tensor (…, M, D).
kernox.linalg
¶
Linear operators and solve (PyKeOps parity).
A SUM reduction that is linear in a j variable (var) defines
the operator K : v ↦ run(..., var=v) from (N, Dv) to (M, Do):
(K v)_i = Σ_j J(x_i, y_j) v_j with J = ∂F/∂var (Do × Dv), constant in
var. :class:LinearOperator exposes it with the interface of
:mod:scipy.sparse.linalg (shape, dtype, matvec, rmatvec,
matmat, T, @), like LazyTensor on the PyKeOps side;
:meth:LinearOperator.solve solves (α I + K) a = b by conjugate gradient
(transcription of PyKeOps' ConjugateGradientSolver, see THIRD_PARTY.md),
differentiable with respect to b and to the other bound inputs.
Linearity is checked symbolically (zero outputs at var = 0,
derivatives free of var) before any launch; never assumed.
LinearOperator
¶
Operator v ↦ run(**inputs, var=v) bound to inputs (run.linear_operator).
shape = (M·Do, N·Dv) and dtype (NumPy) for
:func:scipy.sparse.linalg.aslinearoperator. matvec(v) accepts a
(N, Dv) tensor (returned as (M, Do)), a (N·Dv,) vector or a
(N·Dv, k) matrix (flattened columns); NumPy arrays are converted to the
device of the inputs and returned as NumPy. matvec is differentiable (it is
the reduction itself); so is rmatvec (vector-Jacobian product).
solve(b, *, alpha=DEFAULT_ALPHA, eps=DEFAULT_EPS, maxiter=None, x0=None, return_info=False)
¶
Solves (alpha·I + K) a = b by conjugate gradient (PyKeOps' LazyTensor.solve).
K must be square (M = N, Do = Dv) and, for the conjugate
gradient to converge, symmetric positive definite (alpha regularizes);
symmetry is not checked (like PyKeOps) and is used by the backward
pass (Kᵀ = K). b: (*Bb, M, Do); result (*B, N, Dv),
B being the broadcast of the batch of the bound inputs and of Bb (one system per
element; like PyKeOps, the conjugate gradient operates on the whole
block-diagonal system, with norms over all coefficients). maxiter
defaults to 10·M. Differentiable with respect to b and to the bound tensor inputs,
at any order (create_graph).
conjugate_gradient(linop, b, *, x0=None, eps=DEFAULT_EPS, maxiter=None)
¶
PyKeOps conjugate gradient (pykeops.common.operations.ConjugateGradientSolver).
linop symmetric positive definite; stops when ‖r‖ < max(eps‖b‖, eps)
(norm over all coefficients, like PyKeOps); maxiter defaults to
10 · b.shape[0]. Returns (x, info); warns
(RuntimeWarning) if maxiter is reached.
check_linear(plan, var)
¶
Raises :class:ValidationError if the plan is not a SUM linear in var (j argument).
kernox.ranges
¶
Block-sparse ranges, in the PyKeOps sense.
A :class:Ranges holds, on the device of the inputs, the six integer tensors
of PyKeOps, in the user's orientation (i = Vi, j = Vj):
ranges_i(Ci, 2): blocks of i rows[a, b);slices_i(Ci,): cumulative end, inredranges_j, of the intervals of each block;redranges_j(Ri, 2): intervals[c, d)of j to reduce;ranges_j,slices_j,redranges_i: the transposed triplet (reduction over i; gradients with respect to the j arguments). Optional.
For i in block c: reduction over J(i) = ∪ redranges_j[slices_i[c−1]
: slices_i[c]]; a row covered by no block receives the neutral element of the
reduction; ties go to the smallest j of J(i). Disjoint blocks and
disjoint intervals within a block: checked by with_ranges(r,
validate=True), otherwise an overlap is undefined behavior.
Call: run.with_ranges(r)(**inputs) (see :mod:kernox.runtime).
Triplet
dataclass
¶
(rows, cumulative ends, reduced intervals), in the plan orientation.
Ranges
dataclass
¶
oriented(swapped)
¶
(forward-pass triplet, transposed triplet or None) in the plan orientation.
The plan always reduces over its j rows; swapped (over="i")
exchanges the roles, hence the triplets.
dense(m, n, device=None)
classmethod
¶
A single block, all rows, the whole other axis (equivalent to the call without ranges).
ranges_from_labels(labels_i, labels_j, keep)
¶
Block ranges from sorted labels and a matrix of kept blocks.
labels_i (M,), labels_j (N,): non-decreasing integers in
[0, Ci) / [0, Cj) (points sorted by cluster); keep (Ci, Cj)
boolean. Functional equivalent of pykeops.torch.cluster.from_matrix
applied to the cluster bounds; both triplets are built.
validate_triplet(tr, m, n, side)
¶
Values of a triplet (plan: m rows reduced over n); one host synchronization.
work_list(tr, tile_m)
¶
Tiles (i0, i1, k0, k1) int64 (W, 4), height ≤ tile_m, on the device of the triplet.
[k0, k1): intervals of tr.red to traverse. Torch computation; the
size W requires a host synchronization (the runtime caches the result
by identity of the ranges tensors).
kernox.tuning
¶
Optional autotuning of kernel variants.
Levels (compile(..., tuning=...)):
"estimate"(default):backend.default_variant; no measurement, no wisdom read; deterministic;"wisdom_only": variant from the wisdom if a valid entry exists for the key, otherwiseestimate; no measurement;"measure"/"patient": wisdom if present; otherwise measurement of at most 4 / 32 candidates frombackend.variants(...)(list truncated and overflow logged), on the actual inputs of the call, and recording if the measurement is stable.
Measurement: blocking call, only once per size class
(ceil(2 log2 M), ceil(2 log2 N), ceil(2 log2 nb), ceil(2 log2 1/ρ))
(half-octaves; wisdom v3: nb batch elements, density ρ of the block-sparse
ranges, 0 and 0 without batch or ranges) and per compiled object; compilation excluded from
timing (published separately); 1 warm-up then REPEATS launches
timed with GPU events on the current stream (host clock on CPU);
bounded total time budget (BUDGET_SECONDS, compilation included); at
least the default variant is measured. If the relative spread
(max - min) / median of one of the two best variants exceeds
MAX_SPREAD, the decision is marked unstable and is not persisted.
The result of the call is always recomputed with the selected variant.
Wisdom: one JSON file per device under $KERNOX_CACHE_DIR/wisdom (otherwise
$XDG_CACHE_HOME/kernox/wisdom or ~/.cache/kernox/wisdom), written
atomically (temporary file + os.replace) under an fcntl lock. An
entry with a different format or different versions (device, driver, compiler, generator)
is ignored, as is an entry produced by a lower effort level
than the one requested (patient does not reuse a measure decision).
Backends without variants (default_variant/variants missing, or
compile without a variant parameter): explicit fallback to estimate
(decision source="fallback", message logged once).
TuningDecision
dataclass
¶
Published decision (Reduction.tuning_decisions) for a device and a size class.
size_class(m, n, nb=1, density=1.0)
¶
Size class in half-octaves (wisdom v3), log2(x <= 1) := 0:
(ceil(2 log2 M), ceil(2 log2 N), ceil(2 log2 nb), ceil(2 log2 1/ρ)).
Two sizes in the same class differ by at most a factor sqrt(2) per
axis (v1, in octaves, grouped sizes up to 2x apart and could reuse a
worse decision). nb: batch elements; density: fraction ρ of the pairs (i, j) covered by the block-sparse
ranges (1 without ranges; ρ = 0 counted as one pair). K, the
dimension and the dtype are in the plan key.
lookup(plan_key, backend, identity, sclass, level='wisdom_only')
¶
Recorded variant, or None. An entry produced by a lower
effort than level (measure read by patient) is ignored: the
search is redone and the entry replaced.
export_wisdom(path=None)
¶
All valid wisdom {format, devices: {id: {identity, entries}}}; written to path if given.
import_wisdom(source)
¶
Merges an exported wisdom (dict or path). Returns the number of valid entries imported.
forget_wisdom()
¶
Deletes all wisdom. Returns the number of files deleted.
candidates(backend, plan, device, sizes, level, default)
¶
Deduplicated candidates, default first, truncated to MAX_CANDIDATES[level].
measure(level, compile_variant, candidates_list, inputs, output_shapes_fn, device, budget=None, launch_kwargs=None)
¶
Measures the candidates; returns (winner, measurements, stable, seconds).
compile_variant(v) -> compiled object; output_shapes_fn() -> fresh
temporary outputs. The inputs are only read. launch_kwargs(compiled)
-> keyword arguments of launch (batch=, ranges=; wisdom v3).
kernox.errors
¶
Public kernox exceptions.
All validation errors are raised before any native launch.
UnsupportedError
¶
Bases: NotImplementedError
Operation explicitly not supported (never a silent fallback).
KernoxError
¶
Bases: Exception
Base class for kernox-specific errors (except UnsupportedError).
ValidationError
¶
Bases: KernoxError, ValueError
Invalid input (shape, dtype, device, name, K...) detected before launch.
ConstantConversionError
¶
Bases: KernoxError, ValueError
Constant not representable in the requested dtype (overflow, underflow to 0).
BackendUnavailableError
¶
Bases: KernoxError, RuntimeError
Requested backend missing or not loadable. Never a silent fallback.