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.

Settings

probpipe.config holds the global settings of ProbPipe in four sections:

  1. config.sampling: the default evaluation and draw counts of a call, the controls max_evaluations and num_samples;
  2. config.notation: how many nested levels a label or a notation shows;
  3. config.provenance: the data retained by provenance records, a ProvenanceMode documented on Labels and provenance;
  4. config.prefect: the orchestration of a Function, a WorkflowKind documented on Workflows and reproducibility, and the Prefect task runner.

Assigning a setting sets the session's value. A using block sets temporary values, for one section with config.sampling.using(num_samples=4096) or for several with config.using(sampling={"num_samples": 4096}, notation={"max_depth": 12}). A view's own control, which f.using(...) sets, wins over a block, and a block wins over the session's value. f.using(...) returns a reusable configured copy of f, while config.using(...) is a context manager. The work a call dispatches, such as a function's body run in a worker thread, reads the session's values as they were when the outermost call opened, except those of config.prefect, so a session assignment made during a call applies from the next call on. Workflow scopes determine when each call's provenance mode is fixed.

import probpipe

probpipe.config.notation.max_depth = 12
with probpipe.config.sampling.using(num_samples=4096):
    ...
probpipe.config.reset()

Static and inert settings

Each setting is one of two kinds, which its docstring states.

  1. A static setting can change what a compiled JAX program computes, because ProbPipe code reads it while JAX traces the program, as a kernel inside a joint may read num_samples. A JAX program that ProbPipe compiles for a call is compiled for the values of the static settings in effect, so a call under other values compiles its own and computes with its own values. The static settings are sampling.max_evaluations and sampling.num_samples.
  2. An inert setting changes no computed value, such as how a label renders or whether provenance is recorded, so no compiled JAX program depends on it, and changing it never compiles anything again. Every setting of config.notation, config.provenance, and config.prefect is inert.
from probpipe import Normal, NumericArraySpec, conditional_distribution, sample, workflow_run


@conditional_distribution(given_spec={"mu": NumericArraySpec(())})
def likelihood(mu):
    return Normal("y", mu, 1.0)


model = (likelihood & Normal("mu", 0.0, 1.0))
with workflow_run(seed=0):
    sample(model, 100)  # compiles the joint's JAX program for the session's num_samples, 1024
    with probpipe.config.sampling.using(num_samples=2000):
        sample(model, 100)  # compiles another, for 2000
    with probpipe.config.notation.using(max_depth=12):
        sample(model, 100)  # an inert setting: reuses the JAX program compiled for 1024

The container

config = Config() module-attribute

The global settings of ProbPipe, an instance of Config.

probpipe.core.config.Config()

The global settings of ProbPipe, grouped in sections.

The sections are:

  1. sampling, a SamplingConfig: the default evaluation and draw counts of a call;
  2. notation, a NotationConfig: how many nested levels a label or a notation shows;
  3. provenance, a ProvenanceConfig: how much lineage history a provenance record keeps;
  4. prefect, a PrefectConfig: the orchestration of a Function and the Prefect task runner.

Assigning a setting sets the session's value, which is global to the process. A using block sets temporary values, for one section with config.<section>.using(...) or for several with using::

import probpipe

probpipe.config.sampling.num_samples = 4096
with probpipe.config.using(sampling={"num_samples": 256}, notation={"max_depth": 12}):
    ...
probpipe.config.reset()

A setting resolves from the session's value, then the innermost active block, then a view's own control: f.using(num_samples=...) wins over a block, which wins over the session. f.using(...) returns a reusable configured copy of f, while config.using(...) is a context manager. A block applies in the thread that opens it and in the workers that Function calls inside it dispatch to, whether threads or Prefect workers, and not in another thread. The work a call dispatches reads the session's values as they were when the outermost call opened, except those of prefect, so a session assignment made while the call runs reaches none of that work. Inside a workflow run, a block or an assignment cannot change the provenance mode, as ProvenanceMode states. Assigning a setting inside a block sets the session's value, which applies once the block exits, and reset inside a block restores the session's values while the block still applies. Blocks close in the reverse order of opening, and a block held open by a generator can break that order in two ways, each of which raises RuntimeError:

  • a block closed while a call opened inside it still runs, as when that call closes the generator, keeps applying until the call ends;
  • a call or a block that ends while a block opened inside it is still open, as when the generator outlives it, closes that block with it.

Either way no closed block applies afterwards. A call resolves its settings when it opens. ProbPipe code inside a user's own jax.jit keeps the values in effect while JAX traced it.

Each setting is one of two kinds, which its docstring states:

  1. A static setting can change what a compiled JAX program computes, because ProbPipe code reads it while JAX traces the program, as the size of a Monte Carlo estimate inside a kernel. A JAX program that ProbPipe compiles for a call is compiled for the values of the static settings in effect, so a call under other values compiles its own and never reuses one compiled under the first. The static settings are sampling.max_evaluations and sampling.num_samples.
  2. An inert setting changes no computed value, such as how a label renders or whether provenance is recorded, so no compiled JAX program depends on it. Every setting of notation, provenance, and prefect is inert.
Source code in probpipe/core/config.py
def __init__(self) -> None:
    self._sections: Mapping[str, _Section] = MappingProxyType(
        {
            "sampling": SamplingConfig(),
            "notation": NotationConfig(),
            "provenance": ProvenanceConfig(),
            "prefect": PrefectConfig(),
        }
    )

sampling property

The default evaluation count of a lift and the default draw count of an estimate.

notation property

How many nested levels a label or a notation shows.

provenance property

How much lineage history a provenance record keeps.

prefect property

The orchestration of a Function and the Prefect task runner.

using(**sections)

A block in which the given settings of several sections replace their values.

config.using(sampling={"num_samples": 4096}, notation={"max_depth": 12}) is the block of config.sampling.using(num_samples=4096) and config.notation.using(max_depth=12) together. The class docstring states how a block applies.

Parameters:

Name Type Description Default
**sections Mapping of str to Any

The temporary values of each section, keyed by section name and then by setting name.

{}

Returns:

Type Description
AbstractContextManager

The block, which yields config.

Raises:

Type Description
TypeError

If a name is not a section, naming the sections, if a section is given anything but a mapping, or as a section's using raises.

ValueError

As a section's using raises.

RuntimeError

On entry, if the block sets a provenance mode other than that of the workflow run open in this thread. On exit, if the block closes out of order, as the class docstring states.

Source code in probpipe/core/config.py
def using(self, **sections: Mapping[str, Any]) -> AbstractContextManager[Config]:
    """A block in which the given settings of several sections replace their values.

    ``config.using(sampling={"num_samples": 4096}, notation={"max_depth": 12})``
    is the block of ``config.sampling.using(num_samples=4096)`` and
    ``config.notation.using(max_depth=12)`` together. The class docstring
    states how a block applies.

    Parameters
    ----------
    **sections : Mapping of str to Any
        The temporary values of each section, keyed by section name and
        then by setting name.

    Returns
    -------
    AbstractContextManager
        The block, which yields ``config``.

    Raises
    ------
    TypeError
        If a name is not a section, naming the sections, if a section is
        given anything but a mapping, or as a section's ``using`` raises.
    ValueError
        As a section's ``using`` raises.
    RuntimeError
        On entry, if the block sets a provenance mode other than that of the
        workflow run open in this thread. On exit, if the block closes out
        of order, as the class docstring states.
    """
    unknown = [name for name in sections if name not in self._sections]
    if unknown:
        raise TypeError(f"config.using(): {unknown_names('section', unknown, self._sections)}")
    checked_config_values = {}
    for name, settings in sections.items():
        if not isinstance(settings, Mapping):
            raise TypeError(
                f"config.using(): {name}= must be a mapping of settings, "
                f"got {type(settings).__name__}"
            )
        checked_config_values[name] = self._sections[name]._checked_block_values(
            settings, f"config.using({name}=...)"
        )
    return _config_block(checked_config_values, caller="config.using()", yields=self)

reset()

Restore every section's session settings to their defaults, reading the environment variables again.

An active using block still applies until it exits.

Raises:

Type Description
ValueError

If an environment variable that a section reads is set to an inadmissible value, as each section's reset states.

RuntimeError

Inside a workflow run, if the default provenance mode differs from the run's mode. No section is reset then.

Source code in probpipe/core/config.py
def reset(self) -> None:
    """Restore every section's session settings to their defaults, reading the environment variables again.

    An active ``using`` block still applies until it exits.

    Raises
    ------
    ValueError
        If an environment variable that a section reads is set to an
        inadmissible value, as each section's ``reset`` states.
    RuntimeError
        Inside a workflow run, if the default provenance mode differs from
        the run's mode. No section is reset then.
    """
    _refuse_changing_the_run_provenance_mode(_initial_provenance_mode(), "config.reset()")
    for section in self._sections.values():
        section.reset()

The sections

probpipe.core.config.SamplingConfig()

Bases: _Section

The session's defaults of the evaluation count of a lift and the draw count of an estimate.

Every Function and operation has two count controls, which using sets for one view:

  1. max_evaluations: the maximum number of times a function lifted over laws is evaluated, 256 by default.
  2. num_samples: the number of Monte Carlo draws of a summary, such as a mean with no closed form, or of an approximate conversion, 1024 by default.

A view that sets neither reads the defaults here when it runs, so a setting governs the functions constructed before it::

import probpipe

probpipe.config.sampling.max_evaluations = 1000
probpipe.config.sampling.num_samples = 4096

The settings are global to the process. Their initial values can also be set by the environment variables PROBPIPE_SAMPLING_MAX_EVALUATIONS and PROBPIPE_SAMPLING_NUM_SAMPLES.

Raises:

Type Description
ValueError

On construction, which reads the two environment variables, if either is set to anything but a positive integer. The singleton probpipe.config.sampling is constructed when probpipe is imported, so the import raises.

Source code in probpipe/core/config.py
def __init__(self) -> None:
    self.reset()

max_evaluations property writable

The default of the max_evaluations control, 256 unless the environment sets another.

Function states how a lift spends the count.

A static setting: a JAX program that ProbPipe compiles for a call is compiled for the value in effect, and a call under another value compiles its own.

Raises:

Type Description
TypeError

On assignment of a value that is not an integer, a bool included.

ValueError

On assignment of an integer less than 1.

num_samples property writable

The default of the num_samples control, 1024 unless the environment sets another.

A converter that draws, such as moment matching, takes the converting call's num_samples unless its own num_samples option is given.

A static setting: a JAX program that ProbPipe compiles for a call is compiled for the value in effect, and a call under another value compiles its own.

Raises:

Type Description
TypeError

On assignment of a value that is not an integer, a bool included.

ValueError

On assignment of an integer less than 1.

reset()

Restore both session settings to their defaults, reading their environment variables again.

An active using block that sets a setting still applies until it exits.

Raises:

Type Description
ValueError

If PROBPIPE_SAMPLING_MAX_EVALUATIONS or PROBPIPE_SAMPLING_NUM_SAMPLES is set to anything but a positive integer.

Source code in probpipe/core/config.py
def reset(self) -> None:
    """Restore both session settings to their defaults, reading their environment variables again.

    An active ``using`` block that sets a setting still applies until it exits.

    Raises
    ------
    ValueError
        If ``PROBPIPE_SAMPLING_MAX_EVALUATIONS`` or
        ``PROBPIPE_SAMPLING_NUM_SAMPLES`` is set to anything but a positive
        integer.
    """
    self._max_evaluations: int = _initial_count(
        _MAX_EVALUATIONS_ENV_VAR, _DEFAULT_MAX_EVALUATIONS
    )
    self._num_samples: int = _initial_count(_NUM_SAMPLES_ENV_VAR, _DEFAULT_NUM_SAMPLES)

probpipe.core.config.NotationConfig()

Bases: _Section

Global settings of how labels and notations render.

A tracked term's label and the notation of a law, a kernel, or a function are renderings of the expression the term carries, which nests one level for each value or law it was computed from, as 𝔼[f(beta ~ model; y)] nests four. A rendering shows at most max_depth levels::

import probpipe

probpipe.config.notation.max_depth = 12

The setting is global to the process. A term's label is rendered once, when the term is built, at the setting in effect then.

The initial depth can also be set by the PROBPIPE_NOTATION_MAX_DEPTH environment variable. The depth is an integer from 1 to 64, the number of levels a stored expression keeps, since a rendering of more levels would show no more.

Raises:

Type Description
ValueError

On construction, which reads PROBPIPE_NOTATION_MAX_DEPTH, if the variable is set to anything but an integer from 1 to 64. The section config.notation is constructed when probpipe is imported, so the import raises.

Source code in probpipe/core/config.py
def __init__(self) -> None:
    self.reset()

max_depth property writable

The number of nested levels a label or a notation shows, 8 by default.

A part nested deeper renders as its label, the name of a law or a function, or as … for a value, and str(), repr(), and notation warn with a UserWarning when what they show has such a part. Every label the library derives from one law and a few operators on it nests at most 5 levels, as 𝔼[f(beta ~ model; y)][sample=0] + 1 does, so the default shows each of them in full, while a label derived through a long chain of operations, such as a loop that adds to a value, stays bounded.

A term's label is rendered once, when the term is built, at the setting then, and the term keeps it. The notation of a law, a kernel, or a function is rendered each time it is shown, at the current setting. A stored expression keeps at most 64 levels. A term built over an operand that nests 64 levels stores the whole operand as its label or …, which shows so at any setting, with a UserWarning that says no setting shows it. A loop that adds to a value therefore gives, every 63 steps, a label that shows the last step alone, as … + 1.

An inert setting: it changes no computed value, so no compiled JAX program depends on it.

Raises:

Type Description
TypeError

On assignment of a value that is not an integer, a bool included.

ValueError

On assignment of an integer less than 1 or greater than 64, the number of levels a stored expression keeps.

reset()

Restore the session's settings to their defaults, reading PROBPIPE_NOTATION_MAX_DEPTH again.

An active using block that sets max_depth still applies until it exits.

Raises:

Type Description
ValueError

If PROBPIPE_NOTATION_MAX_DEPTH is set to anything but an integer from 1 to 64.

Source code in probpipe/core/config.py
def reset(self) -> None:
    """Restore the session's settings to their defaults, reading ``PROBPIPE_NOTATION_MAX_DEPTH`` again.

    An active ``using`` block that sets ``max_depth`` still applies until it
    exits.

    Raises
    ------
    ValueError
        If ``PROBPIPE_NOTATION_MAX_DEPTH`` is set to anything but an integer
        from 1 to 64.
    """
    self._max_depth: int = _initial_max_depth()

probpipe.core.config.ProvenanceConfig()

Bases: _Section

Configure the data retained by new provenance records.

Set config.provenance.mode to a ProvenanceMode member::

import probpipe
from probpipe import ProvenanceMode

probpipe.config.provenance.mode = ProvenanceMode.FULL

PROBPIPE_PROVENANCE_MODE supplies the initial mode. Its values are full, lightweight, and off, case-insensitive. ProvenanceMode states when each call's mode is fixed.

Source code in probpipe/core/config.py
def __init__(self) -> None:
    self.reset()

mode property writable

Current global provenance tracking mode.

An inert setting: it changes no computed value, so no compiled JAX program depends on it.

Raises:

Type Description
TypeError

On assignment of a value that is not a ProvenanceMode.

RuntimeError

On assignment inside a workflow run of a mode other than the run's.

reset()

Restore the session's mode to its default (re-reading the env var).

An active using block that sets the mode still applies until it exits.

Raises:

Type Description
RuntimeError

Inside a workflow run, if the default differs from the run's mode.

Source code in probpipe/core/config.py
def reset(self) -> None:
    """Restore the session's mode to its default (re-reading the env var).

    An active ``using`` block that sets the mode still applies until it exits.

    Raises
    ------
    RuntimeError
        Inside a workflow run, if the default differs from the run's mode.
    """
    initial_mode = _initial_provenance_mode()
    _refuse_changing_the_run_provenance_mode(initial_mode, "config.provenance.reset()")
    self._mode: ProvenanceMode = initial_mode

probpipe.core.config.PrefectConfig()

Bases: _Section

Global Prefect orchestration settings.

Attributes:

Name Type Description
workflow_kind WorkflowKind

Default orchestration mode for all Function instances that do not override their own. Initial value is OFF unless the PROBPIPE_WORKFLOW_KIND environment variable is set, in which case its value (off / task / flow / default, case-insensitive) is used. Production callers wanting Prefect orchestration opt in explicitly::

import probpipe
probpipe.config.prefect.workflow_kind = probpipe.WorkflowKind.TASK
task_runner object or None

Prefect task runner instance (e.g., RayTaskRunner()). None means auto-detect: use RayTaskRunner if prefect-ray is installed, then DaskTaskRunner if prefect-dask is installed, otherwise Prefect's built-in default.

Source code in probpipe/core/config.py
def __init__(self) -> None:
    self.reset()

workflow_kind property writable

Current global orchestration mode.

An inert setting: it changes no computed value, so no compiled JAX program depends on it.

task_runner property writable

Explicit task runner, or None for auto-detection.

An inert setting: it changes no computed value, so no compiled JAX program depends on it.

reset()

Restore the session's settings to defaults (re-reading the env var).

An active using block that sets a setting still applies until it exits.

Source code in probpipe/core/config.py
def reset(self) -> None:
    """Restore the session's settings to defaults (re-reading the env var).

    An active ``using`` block that sets a setting still applies until it exits.
    """
    self._workflow_kind: WorkflowKind = _initial_workflow_kind()
    self._task_runner: Any = None

resolve_task_runner()

Return the effective task runner (explicit or auto-detected).

Returns:

Type Description
object or None

A Prefect task runner instance, or None to use Prefect's built-in default.

Source code in probpipe/core/config.py
def resolve_task_runner(self) -> Any:
    """Return the effective task runner (explicit or auto-detected).

    Returns
    -------
    object or None
        A Prefect task runner instance, or ``None`` to use Prefect's
        built-in default.
    """
    runner = self.task_runner
    if runner is not None:
        return runner
    return _auto_detect_task_runner()

Settings in worker processes

Work that a call runs in another process, as the process executor does, carries the call's settings. The prefect section stays behind, so a call in a worker process runs without Prefect orchestration. A setting whose value cannot be pickled travels as a placeholder, and reading it in the worker raises UnshippableSettingError.

UnshippableSettingError

Bases: RuntimeError

A config setting could not be sent to a worker process, and code there read it.

A call that runs work in another process sends its settings with the work. A value that cannot be pickled, such as an object that holds a lock, is sent as a placeholder, and reading it in the worker raises this error. The prefect section is never sent, so a call in a worker process runs without Prefect orchestration. The message names the setting, the class of its value, and why pickling failed.