Skip to content

AI-generated. An AI assistant drafted this page, and no maintainer has reviewed it yet. Please report errors on the issue tracker.

Functions

A Function is an immutable callable with a frozen signature, and calling it with a distribution or a batch as an argument lifts the call over that argument. This page also documents the capabilities a function claims and the errors a call raises. The operations, which are functions with several implementations, are on Operations, and the workflow scopes that key a call's random draws are on Workflows and reproducibility.

Functions

Function(fn, /, *, label=None, input_spec=None, output_spec=None, output_label=None, traceable=None, vectorized=False, differentiable=None, bind=None, **controls)

Bases: TrackedTerm, Annotated

An immutable callable with a frozen signature and optional declarations.

apply binds arguments and validates one raw evaluation, returning the body's result unchanged. Calling the Function runs the installed workflow engine, which adds lifting, execution, result identity, and provenance.

Parameters:

Name Type Description Default
fn Callable

The wrapped Python callable. Its signature is captured at construction.

required
label str

Optional non-empty display alias. Defaults to the callable name, or 𝒻 for a lambda; a callable without a name requires an explicit label.

None
input_spec InputSpec, Mapping, RecordSpec, or OutputSpec or None

Authoritative inputs matching fixed signature parameters by name. Declared inputs cannot accompany variadic parameters. Defaults and construction bindings must satisfy the input spec.

None
output_spec OutputSpec or TermSpec or None

Optional output spec of the result. A bare RecordSpec exposes its fields as outputs; another bare spec is the single output, named by the callable's original name (f for a lambda, result for a nameless callable). Without an output spec, the return type is inferred and the output is named by the same rule. Display aliases never change this default output name. An output spec that names its output but leaves its type unspecified has the type inferred independently for each call. A declared float64 output requires jax_enable_x64=True when the call opens; this applies to apply and to ordinary calls.

None
output_label str or None

Optional result alias. Without one, a call on values labels a value result by the application, as f(2.0), and a returned law or kernel by the function's label, as f(y, mu). Aliases never affect mathematical declarations.

None
traceable bool or None

Whether JAX can trace the callable. True states that jax.jit and jax.vmap both succeed for its input shapes: it acts on array inputs only through jax.numpy and lax, never converts an input to Python or NumPy, never branches in Python on an input's value, and its output shapes depend only on its input shapes. A call then compiles and maps it without testing it first, and a trace that fails raises. False states that it cannot, so it is never traced or tested, and a lifted call evaluates it one point at a time. None, the default, states nothing: the first lifted call, or the first check, for each structure of its inputs traces it once to find out, which runs its Python up to the first operation that fails on a traced value, and later calls with inputs of the same structure read the stored outcome. A callable with side effects, or one that draws from NumPy's random generators, should claim False. Inside a JAX trace an opaque callable runs through a host callback, provided its output spec has concrete numeric shapes and explicit dtypes. Its output is checked on the host; a failed evaluation raises EvaluationError and stops the compiled program. Gradients through it require a derivative, which this boundary does not supply.

None
vectorized bool

Whether the callable evaluates a stack of evaluation points in one call, returning their outputs stacked on a leading axis, with output row i depending only on evaluation point i. False by default.

False
differentiable NumericSpec or None

The differentiability claim: exactly the numeric input values gradients propagate through. None makes no claim.

None
bind Mapping or None

Construction-time values of the wrapped callable's arguments, overridden by call arguments, and the only way to bind an argument at construction. An entry keyed by a name the signature lacks goes to its variadic keyword parameter.

None
**controls Any

The engine's controls, which using revises:

  • workflow_kind (WorkflowKind): orchestration selection; DEFAULT, the default, inherits the workflow configuration.
  • max_evaluations (int or None): the maximum number of times a call lifted over laws evaluates the function, a positive integer. The lift enumerates the empirical arguments whose combinations of atoms number at most max_evaluations, smallest first, and draws the other arguments: max_evaluations joint draws when it enumerates none, and otherwise max_evaluations // n draws for each of the n combinations, at least one. The default is config.sampling.max_evaluations, 256.
  • num_samples (int or None): the number of Monte Carlo draws that a route estimating a summary takes, such as the Monte Carlo mean, and that a conversion of an argument takes where its converter draws, a positive integer. The default is config.sampling.num_samples, 1024.
  • executor (str or None): the name of the executor that runs the evaluations of this function's calls, such as "thread" or a cluster executor a user registers; None, the default, inherits an enclosing call's executor or else selects one automatically. A function JAX can trace is always compiled by "jax".
  • executor_options (Mapping or None): the options of the executor named with them, or of the automatically selected one when no executor is named, such as {"max_workers": 8}; the executor validates them when the call runs. Empty by default. executor and executor_options are set together: setting one with using resets the other.
  • include_inputs (bool): whether the sampling lift retains inputs alongside outputs, False by default.
  • method (str or None): the name of the route that realizes a call; None, the default, selects automatically.
  • exact_only (bool): whether route selection excludes approximate routes, False by default.
  • conversions (Mapping or None): per-parameter conversion settings, keyed by parameter name, each a mapping of the converter's settings.
  • method_options (Mapping or None): the numerical budgets the selected method reads, keyed by option name, such as an MCMC method's warmup and draw counts; the selected method validates the entries when it runs. Empty by default.
  • raw (bool): whether a call returns its result detached from the workflow, False by default.

A call inside a derived operation's formula also takes the exact_only, max_evaluations, and num_samples that the derived route passes down (VI.0). A count set here is a default for every call, so a call that does not read it does not warn, as one whose using view set it does.

{}

Raises:

Type Description
TypeError

For an invalid name, callable, declaration type, or workflow kind, a traceable or vectorized claim that is not a bool, a control of the wrong type, or a keyword that is no control, which the message names; for a label given before the callable, as Function("g", g), or as a second positional argument, as Function(g, "g"); and for a callable given as fn= or func=.

ValueError

For mismatched inputs, invalid defaults or bindings, a nonpositive evaluation or draw count, conversions for a parameter the signature lacks, or invalid output names.

NotImplementedError

If a differentiability claim is given, which Function does not carry yet.

Warns:

Type Description
FutureWarning

For the removed keywords seed, input_template, and output_template, one warning for each one given, pointing at the caller's line.

Notes

The legacy constructor keywords seed, input_template, and output_template emit FutureWarning and are ignored. Use workflow_run(seed=...) for workflow randomness or bind for a wrapped callable's seed parameter. fn is required; the callable name supplies an omitted label. Only the engine's controls are admitted, since a registered method declares no controls of its own: its budgets are entries of method_options.

spec contains only input/output specs. with_label changes the function label and callable metadata; explicit output aliases and output names are preserved. str(f) returns notation, the label followed by the parameters, as predict(x, y), and the repr keeps the label first. using returns a shallow copy with revised controls. A Function stores only the controls set on it, so options reads every other control's default when it is read.

The engine reads three declarations from the Function it runs (V.1): what each parameter accepts, the output spec of the result, and the realization. A Function declares them by its input spec and annotations, its output_spec, and its body; a subclass realized by routes, as an operation is, declares them through _roles, _plan_route_inputs, and _route_candidates.

Source code in probpipe/values/_function_base.py
def __init__(
    self,
    fn: Callable[..., Any],
    /,
    *,
    label: str | None = None,
    input_spec: InputSpec
    | Mapping[str, TermSpec | tuple]
    | RecordSpec
    | OutputSpec
    | None = None,
    output_spec: OutputSpec | TermSpec | None = None,
    output_label: str | None = None,
    traceable: bool | None = None,
    vectorized: bool = False,
    differentiable: NumericSpec | None = None,
    bind: Mapping[str, Any] | None = None,
    **controls: Any,
) -> None:
    _refuse_unknown_controls(controls)
    for key in sorted(_REMOVED_KEYWORDS.keys() & controls.keys()):
        warnings.warn(
            _REMOVED_KEYWORDS[key], FutureWarning, skip_file_prefixes=_WARNING_SKIP_PREFIXES
        )
        controls.pop(key)
    if not callable(fn):
        raise TypeError(f"fn must be callable, got {type(fn).__name__}")
    label = _callable_label(fn, label, subject="Function")
    self._initialize(
        _CallableFunctionImplementation(fn),
        make_signature_info(fn),
        label,
        input_spec=input_spec,
        output_spec=output_spec,
        output_label=output_label,
        traceable=traceable,
        vectorized=vectorized,
        differentiable=differentiable,
        metadata_source=fn,
        bind=bind,
        **controls,
    )

signature property

The independently captured Python calling contract.

spec property

The stored function-kind declaration.

input_spec property

The authoritative inputs, or None when undeclared.

output_spec property

The authoritative output interface, or None when undeclared.

output_label property

The explicit result alias, or the function's name for a derived application.

effective_workflow_kind property

The orchestration mode a call of this function runs under.

The workflow_kind control decides it, and DEFAULT defers to the global config.prefect.workflow_kind, read each time the property is read. When both are DEFAULT, orchestration is OFF. A requested TASK or FLOW falls back to OFF when Prefect is not installed. Until the call engine is installed, a call evaluates plainly, so the mode is OFF.

Warns:

Type Description
UserWarning

If TASK or FLOW is requested and Prefect is not installed.

options property

The effective engine controls, separate from domain arguments.

A control set at construction or by using keeps its value, and every other control reports the framework's default as it reads now.

raw property

The wrapped callable, or the raw evaluator of a private payload.

notation property

The function's label followed by its parameters, as predict(x, y), which str() returns.

The parameters are the names of signature, in order, joined by ", ". A parameter with a default reads name=value, as predict(x, scale=1.0), when the default is a number, a string, None, or an array of no axes, and name=… for any other default. The notation is rendered each time it is shown, at the current config.notation.max_depth. No operation reads the notation.

using(**controls)

Return a copy with revised controls, preserving identity and declarations.

A control given as None resets to its framework default, whatever the constructor or an earlier view set. Raises TypeError for unknown controls, including construction metadata and seed. Invalid control values raise the same errors as construction. A call of the copy warns with UnusedControlWarning for each count set here that nothing the call runs reads.

Parameters:

Name Type Description Default
**controls Any

The revised controls, keyed by the control names that the class's **controls entry lists.

{}

Returns:

Type Description
Self

A shallow copy, which shares the wrapped callable and the declarations.

Source code in probpipe/values/_function_base.py
def using(self, **controls: Any) -> Self:
    """Return a copy with revised controls, preserving identity and declarations.

    A control given as None resets to its framework default, whatever the
    constructor or an earlier view set. Raises TypeError for unknown
    controls, including construction metadata and seed. Invalid control
    values raise the same errors as construction. A call of the copy warns
    with ``UnusedControlWarning`` for each count set here that nothing the
    call runs reads.

    Parameters
    ----------
    **controls : Any
        The revised controls, keyed by the control names that the class's
        ``**controls`` entry lists.

    Returns
    -------
    Self
        A shallow copy, which shares the wrapped callable and the declarations.
    """
    unknown_control_names = controls.keys() - _CONTROL_DEFAULTS.keys()
    if unknown_control_names:
        raise _unknown_controls(unknown_control_names)
    # Only set controls are stored, so dropping one makes it read its default.
    reset_control_names = {
        control_name for control_name, value in controls.items() if value is None
    }
    if controls.keys() & _EXECUTION_CHOICE_CONTROLS:
        # The executor and its options are one unit, so options never pair
        # with an executor named in another layer.
        reset_control_names |= _EXECUTION_CHOICE_CONTROLS - controls.keys()
    kept_controls = {
        control_name: value
        for control_name, value in self._options.items()
        if control_name not in reset_control_names
    }
    control_revisions = {
        control_name: value for control_name, value in controls.items() if value is not None
    }
    validated_controls = _set_controls(
        self._control_defaults(), kept_controls, control_revisions, self.signature
    )
    given_counts = set(self._given_counts)
    forwarded_count_sources = dict(self._forwarded_count_sources)
    for count_name in controls.keys() & set(_COUNT_CONTROLS):
        forwarded_count_sources.pop(count_name, None)
        if controls[count_name] is None:
            given_counts.discard(count_name)
        else:
            given_counts.add(count_name)
    revised_view = self._shallow_copy()
    object.__setattr__(revised_view, "_options", MappingProxyType(validated_controls))
    object.__setattr__(revised_view, "_given_counts", frozenset(given_counts))
    object.__setattr__(
        revised_view, "_forwarded_count_sources", MappingProxyType(forwarded_count_sources)
    )
    return revised_view

check(*args, **kwargs)

Probe a call through the first six steps of the stack, without executing it.

The probe runs the steps a call with the same arguments would run, from resolving the controls to selecting the route, and a view from using probes under the controls of its call. It executes nothing and causes no random event: the body and every conversion stay unexecuted.

Parameters:

Name Type Description Default
*args Any

The call's positional arguments, bound to the signature as the call binds them.

()
**kwargs Any

The call's keyword arguments, bound the same way.

{}

Returns:

Type Description
CallReport

The call's report: for each candidate route whether it is feasible, infeasible with a reason, or unresolved with the declarations it still needs; the selected route when selection can be decided; the planned output spec of the result; the checks deferred to return; the lifted parameters; and the planned conversions.

Raises:

Type Description
TypeError

If an argument does not bind to the signature.

ApplicabilityError

If an argument's kind is not one its parameter accepts, an applicability check fails, or the declarations conflict, as the call raises.

ValueError

If an empty sweep lacks a concrete output spec after input dimensions bind.

ResolutionError

If a conversion has no converter, or the method control names no route of a Function realized by routes.

NotImplementedError

Until the installed engine provides the probe.

Source code in probpipe/values/_function_base.py
@_in_child_call_context("check")
def check(self, *args: Any, **kwargs: Any) -> Any:
    """Probe a call through the first six steps of the stack, without executing it.

    The probe runs the steps a call with the same arguments would run, from
    resolving the controls to selecting the route, and a view from
    :meth:`using` probes under the controls of its call. It executes
    nothing and causes no random event: the body and every conversion stay
    unexecuted.

    Parameters
    ----------
    *args : Any
        The call's positional arguments, bound to the signature as the call
        binds them.
    **kwargs : Any
        The call's keyword arguments, bound the same way.

    Returns
    -------
    CallReport
        The call's report: for each candidate route whether it is feasible,
        infeasible with a reason, or unresolved with the declarations it
        still needs; the selected route when selection can be decided; the
        planned output spec of the result; the checks deferred to return; the
        lifted parameters; and the planned conversions.

    Raises
    ------
    TypeError
        If an argument does not bind to the signature.
    ApplicabilityError
        If an argument's kind is not one its parameter accepts, an
        applicability check fails, or the declarations conflict, as the
        call raises.
    ValueError
        If an empty sweep lacks a concrete output spec after input
        dimensions bind.
    ResolutionError
        If a conversion has no converter, or the ``method`` control names no
        route of a Function realized by routes.
    NotImplementedError
        Until the installed engine provides the probe.
    """
    return _check_engine(self, *args, **kwargs)

apply(*args, **kwargs)

Evaluate one point, validating declarations and returning the raw result.

Python binding errors raise TypeError. Input or output spec violations raise ValueError, including a returned kind that differs from the output spec. Dimension bindings are local to this call. Existing returned objects retain their identity and metadata. A Function realized by routes admits each argument by its role, with no lifting, raising ApplicabilityError for a kind its role refuses; runs the route the engine selects, raising ResolutionError when none applies; and returns the raw form of the result.

Each workflow-owned draw of the evaluation is its own random event, in program order, as in a call of the Function. An evaluation that draws nothing leaves the later draws of its workflow scope unchanged. Inside replay_run it raises ReplayCompatibilityError.

Source code in probpipe/values/_function_base.py
@_in_child_call_context("apply")
def apply(self, *args: Any, **kwargs: Any) -> Any:
    """Evaluate one point, validating declarations and returning the raw result.

    Python binding errors raise TypeError. Input or output spec
    violations raise ValueError, including a returned kind that differs
    from the output spec. Dimension bindings are local to this call.
    Existing returned objects retain their identity and metadata. A Function
    realized by routes admits each argument by its role, with no lifting,
    raising ``ApplicabilityError`` for a kind its role refuses; runs the
    route the engine selects, raising ``ResolutionError`` when none
    applies; and returns the raw form of the result.

    Each workflow-owned draw of the evaluation is its own random event, in
    program order, as in a call of the Function. An evaluation that draws
    nothing leaves the later draws of its workflow scope unchanged. Inside
    ``replay_run`` it raises ``ReplayCompatibilityError``.
    """
    with _apply_scope():
        bound = self.signature.bind_partial(*args, **kwargs)
        values = resolve_function_values(
            self._signature_info,
            dict(bound.arguments),
            bind=self._bind,
            function_name=self.label,
        )
        _, bindings = _bind_function_inputs(
            function_name=self.label, input_spec=self.input_spec, values=values
        )
        result = self._invoke_resolved(values, context=_FunctionInvocationContext(bindings))
        _validate_function_output(
            function_name=self.label,
            output_spec=self.output_spec,
            result=result,
            bindings=bindings,
        )
        return (
            _layout_record_mapping(self.output_spec.term_spec, result)
            if self.output_spec is not None
            else result
        )

__call__(*args, **kwargs)

Call the function through the installed engine (V.1).

The arguments bind to the signature as in apply, and a law or a batch passed where a value is expected lifts the call over it: a law is broadcast and a batch is swept (V.5). The controls come from the construction and using, together with those that a derived route passes down (VI.0), and the call's keywords bind to the wrapped callable. Swept batches align by level name: within each matching level, shapes align from the right and size-one axes broadcast independently of other levels. The sweep carries each level's resulting broadcast shape.

Parameters:

Name Type Description Default
*args Any

The positional arguments of the wrapped callable.

()
**kwargs Any

The keyword arguments of the wrapped callable.

{}

Returns:

Type Description
TrackedTerm or Any

The result at the kind its output spec names, with the call's provenance. It is labeled by an explicit output_label, or else by the application for a value and by the function's label for a returned law or kernel. A broadcast returns the law of the results, and a sweep the batch of them on the swept levels. Under the raw control the result is its raw form, as its raw gives it. Inside a JAX transformation, such as jax.jit, jax.vmap, or jax.grad, a plain call returns its result's raw form (II.4), while an operation and a sweep return their terms.

Raises:

Type Description
TypeError

If an argument does not bind to the signature.

ApplicabilityError

If an argument's kind is not one its parameter accepts, the declarations conflict, or matching levels have shapes that cannot broadcast.

ValueError

If an empty sweep lacks a concrete output spec after input dimensions bind.

ResolutionError

If no route realizes the call.

(ResultKindError, ResultSchemaError)

If the result violates the completed output spec.

Warns:

Type Description
UnusedControlWarning

Once for each count, max_evaluations or num_samples, that this view's using set and that nothing the call ran read, such as num_samples on a call lifted over a law, whose evaluations max_evaluations counts.

Source code in probpipe/values/_function_base.py
@_in_child_call_context("__call__")
def __call__(self, *args: Any, **kwargs: Any) -> Any:
    """Call the function through the installed engine (V.1).

    The arguments bind to the signature as in :meth:`apply`, and a law or a
    batch passed where a value is expected lifts the call over it: a law is
    broadcast and a batch is swept (V.5). The controls come from the
    construction and :meth:`using`, together with those that a
    derived route passes down (VI.0), and the call's
    keywords bind to the wrapped callable. Swept batches align by level name:
    within each matching level, shapes align from the right and size-one
    axes broadcast independently of other levels. The sweep carries each
    level's resulting broadcast shape.

    Parameters
    ----------
    *args : Any
        The positional arguments of the wrapped callable.
    **kwargs : Any
        The keyword arguments of the wrapped callable.

    Returns
    -------
    TrackedTerm or Any
        The result at the kind its output spec names, with the call's
        provenance. It is labeled by an explicit ``output_label``, or else
        by the application for a value and by the function's label for a
        returned law or kernel. A broadcast
        returns the law of the results, and a sweep the batch of them on
        the swept levels. Under the ``raw`` control the result is its raw
        form, as its ``raw`` gives it. Inside a JAX transformation, such as
        ``jax.jit``, ``jax.vmap``, or ``jax.grad``, a plain call returns
        its result's raw form (II.4), while an operation and a sweep
        return their terms.

    Raises
    ------
    TypeError
        If an argument does not bind to the signature.
    ApplicabilityError
        If an argument's kind is not one its parameter accepts, the
        declarations conflict, or matching levels have shapes that cannot
        broadcast.
    ValueError
        If an empty sweep lacks a concrete output spec after input
        dimensions bind.
    ResolutionError
        If no route realizes the call.
    ResultKindError, ResultSchemaError
        If the result violates the completed output spec.

    Warns
    -----
    UnusedControlWarning
        Once for each count, ``max_evaluations`` or ``num_samples``, that
        this view's :meth:`using` set and that nothing the call ran read,
        such as ``num_samples`` on a call lifted over a law, whose
        evaluations ``max_evaluations`` counts.
    """
    return _call_engine(self, *args, **kwargs)

__str__()

The function's notation, as predict(x, y).

Source code in probpipe/values/_function_base.py
def __str__(self) -> str:
    """The function's :attr:`notation`, as ``predict(x, y)``."""
    return self.notation

__repr__()

The public class, the label, the parameters, and the declarations set on the function.

An explicit result alias is shown when one was supplied.

Source code in probpipe/values/_function_base.py
def __repr__(self) -> str:
    """The public class, the label, the parameters, and the declarations set on the function.

    An explicit result alias is shown when one was supplied.
    """
    return term_repr(
        public_class_name(type(self)), self._displayed_label(), self._repr_arguments()
    )

function(_func=None, /, *, label=None, input_spec=None, output_spec=None, output_label=None, traceable=None, vectorized=False, differentiable=None, bind=None, **controls)

function(_func: Callable[..., Any], /, **kwargs: Any) -> Function
function(_func: None = None, /, **kwargs: Any) -> Callable[[Callable[..., Any]], Function]

Decorator to create a Function from a plain function.

Bare usage wraps a function with default Function controls::

@function
def my_func(x, y):
    return x + y

Pass keyword arguments to configure ProbPipe controls at definition time::

@function(max_evaluations=100, executor="thread")
def my_func(x, y):
    return x + y

Keyword arguments passed later to the workflow call itself belong to the wrapped function whenever they can bind to that function. Use workflow.using(...)(...) for one-call ProbPipe controls.

A parameter annotated with a class of raw values, such as pd.Series or jax.Array, receives the raw form of an argument, or of each element or draw that a lift passes to it, when that form is an instance of the class. A function written for pandas therefore runs on a record field that holds a Series::

@function
def differences(c: pd.Series) -> jax.Array:
    return jnp.asarray(c.diff().dropna().to_numpy())

differences(Record({"c": pd.Series([1.0, 2.0, 4.0])}, label="r")["c"])

Parameters:

Name Type Description Default
_func Callable or None

Function being decorated for bare @function usage. Users should not pass this argument by keyword.

None
label str or None

The function label, defaulting to the callable's name, or 𝒻 for a lambda. A callable with none, such as a functools.partial, needs it.

None
input_spec InputSpec or Mapping[str, TermSpec] or None

The authoritative inputs, as Function takes them.

None
output_spec OutputSpec or TermSpec or None

The authoritative result declaration, as Function takes it.

None
output_label str or None

Optional result alias. Without one, a value result describes the application, and a returned law or kernel takes the function's label.

None
traceable bool or None

Whether JAX can trace the function, as Function takes it.

None
vectorized bool

Whether the function takes a stack of evaluation points at once, as Function takes it.

False
differentiable NumericSpec or None

The differentiability claim, as Function takes it.

None
bind Mapping or None

Construction-time values of the wrapped callable's arguments, which call arguments override.

None
**controls Any

The engine's controls, which Function lists.

{}

Returns:

Type Description
Function or Callable

Wrapped Function for bare usage, or a decorator when called with parentheses.

Raises:

Type Description
TypeError

If a keyword is no control, before any callable is wrapped; if traceable or vectorized is not a bool; or if label is omitted for a callable that has no __name__, such as a functools.partial or a callable instance.

Source code in probpipe/functions/_function.py
def function(
    _func: Callable[..., Any] | None = None,
    /,
    *,
    label: str | None = None,
    input_spec: InputSpec | Mapping[str, TermSpec] | None = None,
    output_spec: OutputSpec | TermSpec | None = None,
    output_label: str | None = None,
    traceable: bool | None = None,
    vectorized: bool = False,
    differentiable: NumericSpec | None = None,
    bind: Mapping[str, Any] | None = None,
    **controls: Any,
) -> Function | Callable[[Callable[..., Any]], Function]:
    """Decorator to create a :class:`Function` from a plain function.

    Bare usage wraps a function with default ``Function`` controls::

        @function
        def my_func(x, y):
            return x + y

    Pass keyword arguments to configure ProbPipe controls at definition time::

        @function(max_evaluations=100, executor="thread")
        def my_func(x, y):
            return x + y

    Keyword arguments passed later to the workflow call itself belong to the
    wrapped function whenever they can bind to that function. Use
    ``workflow.using(...)(...)`` for one-call ProbPipe controls.

    A parameter annotated with a class of raw values, such as ``pd.Series`` or
    ``jax.Array``, receives the raw form of an argument, or of each element or
    draw that a lift passes to it, when that form is an instance of the class.
    A function written for pandas therefore runs on a record field that holds
    a ``Series``::

        @function
        def differences(c: pd.Series) -> jax.Array:
            return jnp.asarray(c.diff().dropna().to_numpy())

        differences(Record({"c": pd.Series([1.0, 2.0, 4.0])}, label="r")["c"])

    Parameters
    ----------
    _func : Callable or None
        Function being decorated for bare ``@function`` usage.
        Users should not pass this argument by keyword.
    label : str or None
        The function label, defaulting to the callable's name, or ``𝒻`` for a lambda.
        A callable with none, such as a ``functools.partial``, needs it.
    input_spec : InputSpec or Mapping[str, TermSpec] or None
        The authoritative inputs, as :class:`Function` takes them.
    output_spec : OutputSpec or TermSpec or None
        The authoritative result declaration, as :class:`Function` takes it.
    output_label : str or None
        Optional result alias. Without one, a value result describes the
        application, and a returned law or kernel takes the function's label.
    traceable : bool or None
        Whether JAX can trace the function, as :class:`Function` takes it.
    vectorized : bool
        Whether the function takes a stack of evaluation points at once, as
        :class:`Function` takes it.
    differentiable : NumericSpec or None
        The differentiability claim, as :class:`Function` takes it.
    bind : Mapping or None
        Construction-time values of the wrapped callable's arguments, which
        call arguments override.
    **controls : Any
        The engine's controls, which :class:`Function` lists.

    Returns
    -------
    Function or Callable
        Wrapped Function for bare usage, or a decorator when called
        with parentheses.

    Raises
    ------
    TypeError
        If a keyword is no control, before any callable is wrapped; if
        *traceable* or *vectorized* is not a bool; or if *label* is omitted
        for a callable that has no ``__name__``, such as a
        ``functools.partial`` or a callable instance.
    """
    _refuse_unknown_controls(controls)

    def decorator(func: Callable[..., Any]) -> Function:
        return Function(
            func,
            input_spec=input_spec,
            output_spec=output_spec,
            output_label=output_label,
            traceable=traceable,
            vectorized=vectorized,
            differentiable=differentiable,
            bind=bind,
            **controls,
            label=label,
        )

    if _func is not None:
        return decorator(_func)
    return decorator

FunctionBatch(elements, /, level_names, *, label=None, element=None, axes_per_level=None, provenance=None)

Bases: _ObjectBatch[Callable]

A batch of callables sharing one FunctionSpec.

Parameters:

Name Type Description Default
elements numpy.ndarray or iterable of callable

The callables, as an object array of any shape or a flat iterable.

required
level_names str or sequence of str

One name per level, outermost first.

required
label str

The batch's label. Defaults to a list of its first eight members in row-major order over every batch axis, each as its name and parameters, followed by … when more remain, as [predict(x), f(x)]. A batch of several axes reads as one flat list, and its repr gives the levels.

None
element FunctionSpec

The spec every element satisfies. Defaults to FunctionSpec(), which specifies a callable and neither of its input/output specs.

None
axes_per_level int or sequence of int

How many axes each level holds, outermost first (a single int is one level's count); they must account for every batch axis. Defaults to one axis per level, which requires as many names as there are batch axes. The sizes are read off the elements rather than restated here — they are already fixed by the data, so the only thing left to say is where one level ends and the next begins.

None
provenance Provenance

How this batch was produced.

None

Raises:

Type Description
TypeError

If element is not a FunctionSpec; if an element is not callable, naming the position that failed; if elements is a string, a mapping, or an array that is not dtype=object — each iterates into something other than its elements — or is not iterable at all; or label is omitted and there are no elements.

ValueError

If elements is a zero-dimensional array (one object, with no batch axis to count along); if axes_per_level does not account for every axis the elements are stored in, or gives a count that is not one per level; or if it is omitted and the number of level names does not match the number of axes.

TypeError

If level_names is not a str or a sequence of str, or axes_per_level is not an int or a sequence of ints; a generator, a set, bytes, and a mapping are refused for both.

ValueError

If an axes_per_level count is less than 1, or a level name is empty or contains /.

Notes

A callable has no native stacked form, so the collection is a batch rather than an array. The spec is callable-generic: a plain lambda, a NumPy function, and a Function are all admitted, the wrapper being one such element and not the required type.

This batch stores its elements, and batch[i] is a view of the stored callable: a Function wrapping it under the label derived from the position and the batch's input and output specs, or, for a stored Function, a copy under the derived label that shares its callable. Its provenance records the batch and the stored term. A callable whose signature cannot be inspected, as for some builtins, has no Function view and raises ValueError when indexed. A sub-batch is a view and takes a derived label as any view does.

Examples:

>>> batch = FunctionBatch(
...     [lambda x: x, lambda x: 2 * x],
...     "variant",
...     label="f",
... )
>>> batch.batch_shape
(2,)
>>> batch[1].apply(3)
6
Source code in probpipe/core/_function_batch.py
def __init__(
    self,
    elements: np.ndarray | Iterable[Callable],
    /,
    level_names: NamesLike,
    *,
    label: str | None = None,
    element: FunctionSpec | None = None,
    axes_per_level: AxisCountsLike | None = None,
    provenance: Provenance | None = None,
) -> None:
    super().__init__(
        elements,
        level_names,
        label=label,
        element=element,
        axes_per_level=axes_per_level,
        provenance=provenance,
    )

Binding arguments

Pass an ordinary bound method to Function when a computation uses an object's state. Use bind= for arguments supplied at construction; call arguments replace those bindings, and omitted arguments use the callable's defaults.

from probpipe import Function


class Affine:
    def __init__(self, offset):
        self.offset = offset

    def evaluate(self, x, scale=1.0):
        return (x + self.offset) * scale


compute = Function(Affine(3.0).evaluate, bind={"scale": 2.0})
assert float(compute(1.0)) == 8.0
assert float(compute(1.0, scale=3.0)) == 12.0

A plain operation runs its coordinating route in the calling thread. An executor named on that operation applies to the evaluation points its route requests, including opaque calls inside stored JAX programs. A plain Function body continues to run as an evaluation point on its selected executor.

Opaque functions inside JAX

Wrap code that uses NumPy or an external executable in a Function with traceable=False and a concrete numeric output_spec, including every output leaf's shape and dtype. JAX traces the surrounding computation without running the opaque body. At execution, a host callback sends its evaluation points to an executor and checks the returned values against the output spec. A missing shape, a missing dtype, or a host-only return value is refused during tracing. For example:

import jax
import jax.numpy as jnp
import numpy as np
from probpipe import Function, NumericArraySpec

solver = Function(
    lambda x: np.asarray(x, dtype="float32") + np.float32(1),
    traceable=False,
    output_spec=NumericArraySpec((), dtype="float32"),
)
assert float(jax.jit(lambda x: solver(x))(jnp.float32(2))) == 3

An embedded evaluation cannot draw workflow randomness. Gradients through an opaque function without a derivative are refused, naming that function. A JAX program opened directly by the user uses the default host context; a named executor emits a warning in that case. ProbPipe's stored programs carry the running call's context through a dynamic token.

A failed embedded evaluation stops the compiled program and raises EvaluationError; a host-side executor refusal retains its own exception type when the program runs through ProbPipe. A directly opened JAX program also raises on failure, although JAX wraps the callback's exception.

A declared float64 output requires jax_enable_x64=True when the call opens, for both ordinary calls and apply. Enable it before calling, or declare a float32 output. An undeclared output still records the dtype actually stored.

Differentiability and invertibility

SupportsDifferentiation

Bases: Protocol

An object that declares which of its values gradients propagate through.

The claim is fixed at construction. For a map the template is a sub-schema of its numeric inputs, and for a distribution a sub-schema of its numeric event schema.

differentiable_template property

Exactly the values gradients propagate through.

is_differentiable(x, values=None)

Whether gradients propagate through the named values of x.

Parameters:

Name Type Description Default
x Any

A map or a distribution.

required
values NamedTree or None

The values to test, by their paths. None tests every numeric value of x: its numeric inputs for a map, its numeric event values for a distribution.

None

Returns:

Type Description
bool

True when every value named in values lies in the differentiable template of x, or with no values when the template covers every numeric value of x. False when x does not declare SupportsDifferentiation.

Raises:

Type Description
NotImplementedError

For an object that declares the capability, until the template comparison is implemented.

Source code in probpipe/values/_function_base.py
def is_differentiable(x: Any, values: NamedTree | None = None) -> bool:
    """Whether gradients propagate through the named values of *x*.

    Parameters
    ----------
    x : Any
        A map or a distribution.
    values : NamedTree or None
        The values to test, by their paths. None tests every numeric value of
        *x*: its numeric inputs for a map, its numeric event values for a
        distribution.

    Returns
    -------
    bool
        True when every value named in *values* lies in the differentiable
        template of *x*, or with no *values* when the template covers every
        numeric value of *x*. False when *x* does not declare
        :class:`SupportsDifferentiation`.

    Raises
    ------
    NotImplementedError
        For an object that declares the capability, until the template
        comparison is implemented.
    """
    if not isinstance(x, SupportsDifferentiation):
        return False
    raise NotImplementedError(
        "is_differentiable() is not implemented yet for an object that declares "
        "SupportsDifferentiation"
    )

SupportsInverse

Bases: Protocol

An invertible map, whose forward is the claiming Function's apply.

A class whose instances are invertible only in some configurations also defines the guard _inverse_guard(), and is_invertible reads the claim together with it. The guard returns one of:

  • a bool: whether the inverse is available;
  • None: the answer is unresolved;
  • a Feasibility: the full report.

is_invertible(f)

Whether f claims SupportsInverse and its guard admits the claim.

Parameters:

Name Type Description Default
f Any

The object to test, usually a Function.

required

Returns:

Type Description
bool

True when f claims the capability and either defines no _inverse_guard or its guard reports the inverse feasible. False when f does not claim the capability, or its guard reports the inverse infeasible or unresolved.

Source code in probpipe/values/_function_base.py
def is_invertible(f: Any) -> bool:
    """Whether *f* claims :class:`SupportsInverse` and its guard admits the claim.

    Parameters
    ----------
    f : Any
        The object to test, usually a :class:`Function`.

    Returns
    -------
    bool
        True when *f* claims the capability and either defines no
        ``_inverse_guard`` or its guard reports the inverse feasible. False when
        *f* does not claim the capability, or its guard reports the inverse
        infeasible or unresolved.
    """
    if not isinstance(f, SupportsInverse):
        return False
    guard = getattr(f, "_inverse_guard", None)
    return True if guard is None else _guard_admits(guard())

SupportsLogDetJacobian

Bases: Protocol

A map with a tractable log-determinant of its Jacobian.

Checking a call

CallReport(routes=(), selected=None, deferred=(), result=None, lifted=(), conversions=(lambda: MappingProxyType({}))(), methods=(lambda: MappingProxyType({}))(), execution=ExecutionReport()) dataclass

What check reports about a call, without executing it (V.1).

A route's report is a MethodInfo named by the route, and by route/method for the method a registry route selects. The repr follows the repr convention (II.4), and in a notebook the report displays as a table with one row per route.

Attributes:

Name Type Description
routes tuple of MethodInfo

Each probed route's report, in selection order: feasible, infeasible with a reason, or unresolved with the declarations it needs.

selected MethodInfo or None

The selected route's report, or an infeasible report naming no route when none applies; None when selection cannot be decided, since a route ranked above every feasible one is unresolved.

deferred tuple of str

The checks left to the return.

result OutputSpec or None

The planned output spec of the result, or None when only the return settles it.

lifted tuple of str

The parameters whose arguments lift or sweep.

conversions Mapping of str to ConversionInfo

The planned conversion of each parameter that converts.

methods Mapping of str to tuple of str

The methods of each registry the routes delegate to, in its selection order, keyed by the names of those routes joined by ", ". The routes' reports leave them out, so each registry's methods are listed once.

execution ExecutionReport

How the call would run the evaluation points it asks for: one report per callable, with the executor and the executors it rejected. The repr shows it only when a callable is opaque or runs on an executor other than jax.

feasible property

Whether a route is selected: False when none applies, None when undecided.

route property

The selected route's name, or None.

method property

The registry method the selected route delegates to, or None.

exact property

The selected implementation's exactness, or None when none is selected.

pending property

What an undecided selection waits on: the needs of each unresolved route.

description property

The selected report's description, which names every route tried when none applies.

__repr__()

The fields the report sets, as a call of its constructor (II.4).

Source code in probpipe/functions/_call.py
def __repr__(self) -> str:
    """The fields the report sets, as a call of its constructor (II.4)."""
    keywords: list[tuple[str, str]] = []
    if self.routes:
        keywords.append(("routes", sequence_repr(repr(info) for info in self.routes)))
    if self.selected is not None:
        keywords.append(("selected", repr(self.selected)))
    if self.deferred:
        keywords.append(("deferred", sequence_repr(repr(item) for item in self.deferred)))
    if self.result is not None:
        keywords.append(("result", repr(self.result)))
    if self.lifted:
        keywords.append(("lifted", format_names(self.lifted)))
    if self.conversions:
        converted = {name: repr(info) for name, info in self.conversions.items()}
        keywords.append(("conversions", mapping_repr(converted)))
    if self.methods:
        listed = {route: format_names(names) for route, names in self.methods.items()}
        keywords.append(("methods", mapping_repr(listed)))
    if self.execution._runs_more_than_compiled_code():
        keywords.append(("execution", repr(self.execution)))
    return call_repr("CallReport", keywords=keywords)

check also reports how the call will run its evaluation points: one report per callable that a lifted call or a sweep evaluates, with the executor that will run them and the executors it rejected.

ExecutionReport(evaluations=()) dataclass

How a call will run the evaluation points it asks for, as check reports it (V.9).

One call may send one callable to jax and another to a cluster, so the report holds one EvaluationReport per callable.

Attributes:

Name Type Description
evaluations tuple of EvaluationReport

One report per callable whose evaluation points the call evaluates, in the order the call asks for them. A plain call on values evaluates its function once, in no set of evaluation points, and reports none.

__repr__()

The reports, as a call of the constructor (II.4).

Source code in probpipe/core/_executors.py
def __repr__(self) -> str:
    """The reports, as a call of the constructor (II.4)."""
    return call_repr(
        "ExecutionReport",
        keywords=(("evaluations", sequence_repr(repr(report) for report in self.evaluations)),),
    )

EvaluationReport(callable_name, num_evaluation_points, traceable, traceability_source, executor, rejected=(), failure_rule='raise') dataclass

How a call will run the evaluation points of one callable, as check reports it (V.9).

Attributes:

Name Type Description
callable_name str

The name of the callable.

num_evaluation_points int or None

The number of its evaluation points; None when the code that asks for them decides it while the call runs.

traceable bool

Whether JAX can trace the callable for these evaluation points.

traceability_source {'claimed', 'probed'}

"claimed" when the callable's traceable claim says whether it traces, and "probed" when its stored probe result does.

executor MethodInfo

The executor that will run the evaluation points. It is infeasible, with the reason, when the executor named for the callable cannot run them, and the call then raises ResolutionError.

rejected tuple of MethodInfo

Each executor tried first that cannot run the evaluation points, with its reason.

failure_rule {'raise', 'drop'}

What the call does when an evaluation point fails: "raise" raises EvaluationError, naming every failed evaluation point.

Examples:

check of a call lifted over a law, of a function that claims traceable=False, reports its 256 draws running one after another::

forward.check(prior).execution.evaluations[0]
# EvaluationReport(callable_name='forward', num_evaluation_points=256,
#                  traceable=False, traceability_source='claimed',
#                  executor=MethodInfo(True, method_name='sequential', exact=True),
#                  rejected=(MethodInfo(False, method_name='jax', ...),),
#                  failure_rule='raise')

__repr__()

Every field, as a call of the constructor (II.4).

Source code in probpipe/core/_executors.py
def __repr__(self) -> str:
    """Every field, as a call of the constructor (II.4)."""
    return call_repr(
        "EvaluationReport",
        keywords=(
            ("callable_name", repr(self.callable_name)),
            ("num_evaluation_points", repr(self.num_evaluation_points)),
            ("traceable", repr(self.traceable)),
            ("traceability_source", repr(self.traceability_source)),
            ("executor", repr(self.executor)),
            ("rejected", sequence_repr(repr(info) for info in self.rejected)),
            ("failure_rule", repr(self.failure_rule)),
        ),
    )

ApplicabilityError

Bases: TypeError

The arguments or declarations of a call violate its call contract.

Raised when an argument's kind is not one its parameter accepts, when swept levels do not align, and when the declarations of a call conflict. The message names the parameter, what it accepts, and what arrived.

ResultKindError

Bases: TypeError

A function returned a term of another kind than its output spec names.

This is a defect of the function's return contract, not a failure to admit the caller's arguments.

ResultSchemaError

Bases: ValueError

A function's result is incompatible with its completed output spec.

Raised for incompatible structure, dimensions, dtype, or support, and for a violated declared output interface. This is a defect of the function's return contract, not a failure to admit the caller's arguments.

Counts a call does not use

A call warns when its using view sets max_evaluations or num_samples and nothing the call runs reads that count. pushforward.using(num_samples=10)(x, square) warns, because a call lifted over a distribution evaluates its function max_evaluations times and takes no Monte Carlo draws, and the warning says to set max_evaluations=10 instead. A count set when a Function is constructed, by a config block, or as the session's value is a default and never warns.

UnusedControlWarning

Bases: UserWarning

A control given to a call through using changed nothing the call did.

A call that succeeds warns once for each count, max_evaluations or num_samples, that its using view set and that no code running for the call read. A count set when the Function was constructed, or by a config block or the session, is a default for every call and never warns. To make the warning an error::

import warnings
warnings.simplefilter("error", probpipe.UnusedControlWarning)

Failed evaluations

A call that evaluates a function many times, such as a call lifted over a distribution, runs every evaluation and keeps the outputs that succeeded. When some evaluations fail, the call then raises EvaluationError, which names each failed one and is chained to the first failure's exception.

EvaluationError(failures, outputs, *, origin, point_noun='evaluation point')

Bases: RuntimeError

Evaluation points of a call failed.

The call ran every evaluation point and kept the outputs that succeeded, then raised. The error is chained to the first failure's exception when it is available, so the traceback points into the code that raised.

Parameters:

Name Type Description Default
failures iterable of EvaluationFailure

The failed evaluation points.

required
outputs iterable

Each evaluation point's output, in order, None where one failed.

required
origin str

The callable or the site, which the message names.

required
point_noun str

The word for one evaluation point in the message, such as "draw".

'evaluation point'

Attributes:

Name Type Description
failures tuple of EvaluationFailure

Every failed evaluation point, in order.

outputs tuple

Each evaluation point's output, in order, None where one failed, kept for diagnosis.

Examples:

A simulator that fails at one of 200 draws raises::

EvaluationError: evaluation of 'forward' failed at 1 of 200 evaluation points:
draw 17: CalledProcessError: Command '...' returned non-zero exit status 3.
Source code in probpipe/core/_evaluation_points.py
def __init__(
    self,
    failures: Iterable[EvaluationFailure],
    outputs: Iterable[Any],
    *,
    origin: str,
    point_noun: str = "evaluation point",
) -> None:
    self.failures = tuple(sorted(failures, key=lambda failure: failure.point_index))
    self.outputs = tuple(outputs)
    listed_failures = "; ".join(
        f"{point_noun} {failure.point_index}: {_failure_cause(failure)}"
        for failure in self.failures[:_LISTED_FAILURES]
    )
    unlisted_count = len(self.failures) - _LISTED_FAILURES
    if unlisted_count > 0:
        listed_failures += f"; and {unlisted_count} more"
    super().__init__(
        f"evaluation of {origin!r} failed at {len(self.failures)} of "
        f"{count(len(self.outputs), 'evaluation point')}: {listed_failures}"
    )