Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Architecture

1. The dispatch pattern

Every operator follows the same three-line core, as MeanScalar does in operators/_reduce.py:

from typing import Any

from pipekit_ops import Operator

from pipekit_array.named import array_namespace


class MeanScalar(Operator):
    """Reduce an array to a scalar (or per-axis means) via xp.mean."""

    def __init__(
        self,
        axis: int | tuple[int, ...] | None = None,
        keepdims: bool = False,
    ) -> None:
        self.axis = axis
        self.keepdims = keepdims

    def _apply(self, x: Any) -> Any:
        xp = array_namespace(x)
        return xp.mean(x, axis=self.axis, keepdims=self.keepdims)

    def get_config(self) -> dict[str, Any]:
        return {"axis": self.axis, "keepdims": self.keepdims}

The array_namespace(x) call is the entire backend-dispatch story. It returns the module-like object that exposes the Array API surface: numpy, jax.numpy, cupy, dask.array, or array_api_compat.torch for PyTorch (which needs the [compat] extra, because torch tensors do not implement __array_namespace__ themselves). The operator never imports a specific backend; the input array picks.

The shipped MeanScalar also turns a list axis (as it comes back from JSON) into a tuple, and implements compute_output_signature; the sketch leaves both out.

2. The four shape rules

Every pipekit-array operator obeys these four rules. Reviewers should treat any violation as a blocking comment.

R1. Pure functions, no in-place mutation

# Don't:
x[0] = 0
return x

# Do:
xp = array_namespace(x)
zero = xp.zeros_like(x[:1])
return xp.concat([zero, x[1:]], axis=0)

JAX immutability is the strict constraint that drives this. NumPy and PyTorch users won’t notice, CuPy follows NumPy’s semantics, and dask is immutable by design.

R2. Single namespace per _apply call

# Don't:
xp1 = array_namespace(x)
xp2 = array_namespace(y)  # a different namespace?
return xp1.add(x, y)  # crashes if y is JAX and x is NumPy

# Do:
xp = array_namespace(x, y)  # NumPy joins JAX (A24); another mix raises TypeError
return xp.add(x, y)

array_namespace(x, y) is the standard’s way to assert “both inputs are on the same backend” and pick the namespace; with NumPy next to JAX it picks JAX’s (A24). Operators with several array inputs always use the multi-argument form.

The named layer has its own form of this rule: join_backends in named/_dispatch.py raises BackendError when the inputs of dot, combine, concat, stack or take_along sit on more than one backend.

R3. No backend-name conditionals

# Don't:
xp = array_namespace(x)
if xp.__name__ == "jax.numpy":
    return jax_specific_path(x)
else:
    return generic_path(x)

# Do:
xp = array_namespace(x)
return generic_path(x, xp)  # via xp dispatch only

If an operator genuinely needs a per-backend path (for example an FFT that is not in the Array API standard), it does not belong in pipekit-array. It belongs in a per-backend sister package (pipekit-jax, a future pipekit-torch) or in user code (ADR A4).

As built. The dim-level functions bend this rule in a few places, each confined to a helper in named/ rather than written inside an operator:

R4. Output dtype matches input dtype (default)

# Don't:
xp = array_namespace(x)
return xp.astype(xp.mean(x), xp.float64)  # silently upcast

# Do:
xp = array_namespace(x)
return xp.mean(x)  # the Array API mean keeps a floating input's dtype

The principle of least surprise: a float32 input gives a float32 output. Operators that must change dtype take an explicit dtype argument.

As built. The dim-level functions keep this rule (gate G8 of Dim-level functions: the missing ones §7):

3. The areas

src/pipekit_array/
├── __init__.py       # the named functions, the kernels and the operators
├── _recorded.py      # where a saved pipeline says that an operator lives
├── arrays/           # functions of plain arrays              ([numpy,compat])
│   ├── _backend.py      namespace_of, floating_inputs, as_inexact, concrete
│   ├── _host.py         like, constants_like, table_like, boolean_like
│   ├── _numerics.py     divide_or_nan, the safe roots, stand_in
│   ├── _indexing.py     set_at, add_at, multiply_at, pad
│   ├── _transforms.py   vmap, scan, stop_gradient, optimization_barrier
│   ├── _checks.py       check_values, require_floating
│   ├── _reductions.py   weighted_sum, weighted_mean, Groups
│   └── _records.py      register_record
├── named/            # functions of carriers with dimension names
│   ├── _carrier.py      DimArray, DimArrayAdapter
│   ├── _dispatch.py     array_namespace, join_backends, and what the rest share
│   ├── _select.py  _reduce.py  _shape.py  _shift.py  _window.py  _join.py  _map.py
│   └── _batches.py  _rows.py
├── kernels/          # one array function on every carrier
│   ├── _spec.py  _run.py  _op.py
│   └── _elementwise.py                                       ([numpy,compat])
├── operators/        # the operator twins, in files named as in named/
├── bridges/          # xarray.py, einx.py, sklearn.py: one extra each
└── testing/          # the test kit

An area imports only from the ones before it, in the order arrays, named, kernels, operators, bridges; testing imports from all of them. named and operators do not import arrays, because they run with no extra. tests/test_areas.py enforces both.

A name is imported from its area (from pipekit_array.arrays import floating_inputs), and the files in an area are private. The package itself re-exports the named functions, the kernels, the operators, Estimator and BackendError; arrays and testing are imported by name.

Not built from the v0.1 catalogue: the numeric QC family, the array-aware Histogram and ModelOp. The first two would be new files of operators, and ModelOp a bridge.

4. The array_namespace shim

The standard needs a small wrapper because Array API namespace discovery has two paths:

  1. Native conformance (NumPy 2.0+, JAX, CuPy): the array implements __array_namespace__() directly.

  2. Wrapped conformance (PyTorch, older NumPy, dask edge cases): the array-api-compat library provides the namespace.

The shipped shim in named/_dispatch.py, simplified:

# pipekit_array/named/_dispatch.py
def array_namespace(*xs: Any) -> Any:
    """Return the Array API namespace shared by all inputs."""
    compat_ns = _compat_namespace()  # looked up once, then cached
    if compat_ns is not None:
        try:
            return compat_ns(*xs)
        except TypeError as exc:
            # re-raised with the same wording as the path below
            raise TypeError(_NO_BACKEND_MSG) from exc

    namespaces = set()
    for x in xs:
        ns = getattr(x, "__array_namespace__", None)
        if ns is None:
            raise TypeError(f"Input of type {type(x).__name__!r} ...")
        namespaces.add(ns())
    if len(namespaces) == 0:
        raise TypeError(_NO_BACKEND_MSG)
    if len(namespaces) > 1:
        names = sorted({ns.__name__ for ns in namespaces})
        raise TypeError(_multi_backend_msg(names))
    return next(iter(namespaces))

Three details differ from the first design:

The compat shim is a soft dependency: pipekit-array works without it, and installing it widens backend coverage. It ships as the [compat] extra (array-api-compat>=1.4), which PyTorch inputs need.

5. Integration with pipekit core

pipekit-array operators are just pipekit_ops.Operator subclasses. They inherit:

The signature integration is the only piece pipekit-array adds beyond “a bag of operators”: it makes the new operators show up usefully in Sequential.summary output without special-casing.

6. Integration with sister libraries

The planned pattern from Report 3 §1.5:

# geotoolz/qc.py
# proposed (phase C): pipekit_array.qc does not exist yet
from pipekit_array.qc import AssertValueRange as _AssertValueRange


class AssertValueRange(_AssertValueRange):
    """GeoTensor-aware value-range assertion.

    Same numeric logic, but reads GeoTensor's `fill_value` as the
    implicit min/max bounds if the user doesn't specify them.
    """

    def __init__(self, min_val=None, max_val=None, on_fail="raise") -> None:
        super().__init__(min_val=min_val, max_val=max_val, on_fail=on_fail)

geotoolz and xr_toolz add carrier-specific defaults on top of the generic logic. The numeric work (xp.any(x < min_val)) lives once, in pipekit-array.

xr_toolz operators that wrap an xr.DataArray would typically:

  1. extract .data (the underlying array) and .dims;

  2. apply the pipekit-array operator to .data;

  3. rebuild the xr.DataArray with the same coords, dims and attrs.

The extraction and reconstruction are xarray-specific; the array maths is pipekit-array’s. It is the same delegation pattern as geotoolz, on a different carrier.

As built. For the dim-level functions the delegation already lives in pipekit-array: the [xarray] adapter (pipekit_array.bridges.xarray) is registered lazily with pipekit_ops, so rename, window, dot and the rest run on an xr.DataArray directly and keep its coordinates. geoarray carriers reach the same functions through their own registered adapter (ADR A9).

7. Integration with pipekit-train

pipekit-train ships EquinoxModelOp in-package as its trained-model wrapper, with pipekit_jax.JaxModelOp as the weight-blob round-trippable upgrade. The Lightning backend was dropped and the Keras backend returns its own KerasModelOp (pipekit-train D15, D20), so pipekit_array.ModelOp (not built yet) is the wrapper for models that no pipekit-train backend trains. The boundary:

BackendTrained-model opLives in
EquinoxEquinoxModelOp (light) / JaxModelOp (round trip)pipekit-train / pipekit-jax
Keras 3KerasModelOp (round trip)pipekit-train
sklearnModelOppipekit-array (not built)

This implements pipekit-train’s open promise in its docs/design/api/adapters.md: “wrap the final module’s nn.Module in pipekit-array.ModelOp and return” (ADR A8). For sklearn on named carriers, Estimator already ships ([sklearn]): it fits and applies an estimator by dim name through to_rows and from_rows.

8. Test matrix

The CI surface fans out across backends. The pattern, as in tests/operators/test_reduce.py:

# tests/test_reduce.py
from pipekit_array import MeanScalar


def test_mean_scalar_full_reduction(backend, make_array):
    x = make_array(backend, shape=(4, 8), seed=0)
    out = MeanScalar()(x)
    assert out.ndim == 0

backend is a conftest fixture parametrised over ("numpy", "jax", "torch"), and make_array returns the _make_array(backend, shape, seed) helper, which calls pytest.importorskip and returns a small random float32 array. Tests that need only one backend (numpy is the cheapest) leave the backend fixture out.

The first design kept cupy and dask out of the core CI matrix, because CuPy needs a GPU and dask shifts the timing a lot, and planned opt-in make test-cupy / make test-dask targets. As built, neither target exists:

Per-backend extras would be validated separately by their own CI shape gate, mirroring the uv sync --extra equinox discipline pipekit-train uses (one make target per extra).