Skip to content

Model binding and fitting

The model interface binds external values using the types and roles checked from QVR, then applies a reusable inference method.

Declare explicit inputs in the runtime telescope of a program header, as in program regression(x : Tensor[Real]([Row]), y : Tensor[Real]([Row])) : Row -> Out. Static objects, morphisms, and extents use a preceding bracketed telescope. Annotations constrain values; observe determines which inputs are responses. The parameter reference explains the convention across language constructs.

MCMCMethod, VariationalMethod, and PathfinderMethod return ModelFit. SMCMethod instead returns the existing SMCResult with its particles, normalizing-constant estimate, and tempering diagnostics. All four consume the same checked BoundModel, and their result contracts remain specific to the inference method. Pathfinder retains independent approximate draws. MCMCMethod(cores=2) runs the chains in two worker processes that recompile the model from its source and binding, with the result of the serial run (parallel chains).

An existing ModelFit exposes fit.evidence(sampler). This applies the same SMC driver to the retained checked program and data, including a fit initialized with a variational guide. The guide and retained posterior draws do not enter the evidence calculation. Observation weights define a powered target whose normalizing constant need not be an ordinary data probability.

ModelFit.posterior_epred collects native conditional response expectations with retained chain/draw axes. ModelFit.conditional_effects applies this collector once to a bounded predictor grid, using the checked nominal row axis to distinguish row inputs from unrelated fitted tensors. Both reuse the fitted latent layout and deterministic parameters; neither fits a new posterior. See source conditional effects for conditioning, Scan addressing, and finite-moment approximation semantics.

import torch
from quivers.inference import SMC
from quivers.inference.mcmc import MetropolisKernel, RandomWalkProposal
from quivers.modeling import Model, SMCMethod

source = """object One:FinSet 1
object Out:Real 1
program model(y:Real):One->Out
    sample mu <- Normal(loc=0.0,scale=1.0)
    observe y <- Normal(loc=mu,scale=1.0)
    return mu
export model
"""
result = Model(source).fit(
    {"y": torch.tensor(0.7)},
    method=SMCMethod(sampler=SMC(
        MetropolisKernel(RandomWalkProposal(0.5)),
        num_particles=16, num_mcmc_steps=1, num_pilot_steps=0, seed=7,
    )),
)
assert result.num_particles == 16
assert result.temperatures[0] == 0 and result.temperatures[-1] == 1

model

Compile, bind, and inspect QVR models through checked input metadata.

ModelSchema didactic-model

ModelSchema(*, entry: ProgramEntry = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

The checked input contract of one QVR program.

PARAMETER DESCRIPTION
entry

Typed parameters, site roles, plates, and static binders. The entry is immutable and compared by value, without rendering away its types.

TYPE: ProgramEntry DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

inputs property

inputs: tuple[ProgramParameter, ...]

External data and observations, in checked parameter order.

RETURNS DESCRIPTION
tuple[ProgramParameter, ...]

Typed external parameters in declaration order.

observations property

observations: tuple[str, ...]

The names of the values scored by observation steps.

RETURNS DESCRIPTION
tuple[str, ...]

Observation names, excluding covariates and index maps.

types property

types: dict[str, TypeExpr]

External symbols mapped to their original checked types.

RETURNS DESCRIPTION
dict[str, TypeExpr]

The typed external input contract.

describe

describe() -> dict[str, dict[str, str]]

Render the external input contract for display.

RETURNS DESCRIPTION
dict[str, dict[str, str]]

Each input's role, readable type, and optional value restriction.

Source code in src/quivers/modeling/model.py
def describe(self) -> dict[str, dict[str, str]]:
    """Render the external input contract for display.

    Returns
    -------
    dict[str, dict[str, str]]
        Each input's role, readable type, and optional value restriction.
    """
    return {
        p.name: {
            "role": p.role,
            "type": render_static(p.type),
            **({"constraint": p.constraint} if p.constraint is not None else {}),
        }
        for p in self.inputs
    }

InferenceMethod

Bases: Protocol

An inference implementation whose result type is chosen by the method.

Implementations may return draws, messages, a MAP certificate, or another result. They must check their own execution and differentiation requirements.

run

run(model: BoundModel) -> Result

Run inference on a bound model.

PARAMETER DESCRIPTION
model

Checked program, data, input, and schema.

TYPE: BoundModel

RETURNS DESCRIPTION
Result

The method's own result type.

Source code in src/quivers/modeling/model.py
def run(self, model: BoundModel) -> Result:
    """Run inference on a bound model.

    Parameters
    ----------
    model : BoundModel
        Checked program, data, input, and schema.

    Returns
    -------
    Result
        The method's own result type.
    """
    ...

Model

Model(source: str, *, entry: str | None = None, families: FamilyCatalog | None = None)

A reusable QVR source whose finite dimensions specialize at data binding.

PARAMETER DESCRIPTION
source

QVR source, optionally declaring objects as FinSet _.

TYPE: str

entry

Program to select. Defaults to the first exported program, or the only program when none is exported.

TYPE: str or None DEFAULT: None

families

Immutable native family definitions for this model's compilation.

TYPE: FamilyCatalog or None DEFAULT: None

Source code in src/quivers/modeling/model.py
def __init__(
    self,
    source: str,
    *,
    entry: str | None = None,
    families: FamilyCatalog | None = None,
) -> None:
    self.families = families
    self.source = source
    self.syntax: Module = parse(source)
    names = [s.name for s in self.syntax.statements if isinstance(s, ProgramDecl)]
    if entry is None:
        exported = [
            s.expr.name
            for s in self.syntax.statements
            if isinstance(s, ExportDecl)
            and isinstance(s.expr, ExprIdent)
            and s.expr.name in names
        ]
        if exported:
            entry = exported[0]
        elif len(names) == 1:
            entry = names[0]
        else:
            raise ValueError(f"select an entry from {names}")
    if entry not in names:
        raise ValueError(f"unknown program {entry!r}; choose from {names}")
    self.entry = entry
    checked = lower_qvr_to_qiec(self.syntax, families=families)
    self.checked_module = checked
    self._checked_source = (self.syntax, checked)
    self._checked_families = families
    typed_entry = next((e for e in checked.entries if e.name == entry), None)
    if typed_entry is None:
        raise CompileError(f"entry {entry!r} has no checked input contract")
    self.schema = ModelSchema(entry=typed_entry)

from_file classmethod

from_file(path: str | Path, *, entry: str | None = None, families: FamilyCatalog | None = None) -> Model

Read a QVR model from a file.

PARAMETER DESCRIPTION
path

UTF-8 source file.

TYPE: str or Path

entry

Program to select.

TYPE: str or None DEFAULT: None

families

Immutable native family definitions for this compilation.

TYPE: FamilyCatalog or None DEFAULT: None

RETURNS DESCRIPTION
Model

Parsed reusable model.

Source code in src/quivers/modeling/model.py
@classmethod
def from_file(
    cls,
    path: str | Path,
    *,
    entry: str | None = None,
    families: FamilyCatalog | None = None,
) -> Model:
    """Read a QVR model from a file.

    Parameters
    ----------
    path : str or Path
        UTF-8 source file.
    entry : str or None
        Program to select.
    families : FamilyCatalog or None
        Immutable native family definitions for this compilation.

    Returns
    -------
    Model
        Parsed reusable model.
    """
    return cls(
        Path(path).read_text(encoding="utf-8"), entry=entry, families=families
    )

fit

fit(data: Mapping[str, object], *, method: InferenceMethod[Result], parameters: Mapping[str, object] | None = None, input: Tensor | None = None, seed: int = 0, sample_prior: PriorMode = 'no', num_prior_samples: int = 100, prior_seed: int = 1, snapshot_policy: SnapshotPolicy = 'clone') -> Result

Bind external data and apply an inference method in one call.

PARAMETER DESCRIPTION
data

External values, with roles inferred from QVR.

TYPE: Mapping[str, object]

method

Inference configuration, including its own random seed and budgets.

TYPE: InferenceMethod[Result]

parameters

Static specialization arguments passed to binding.

TYPE: Mapping[str, object] or None DEFAULT: None

input

One-run domain input, if the program reads one.

TYPE: Tensor or None DEFAULT: None

seed

Compilation seed, independent of the method's inference seed.

TYPE: int DEFAULT: 0

sample_prior

Ordinary fitting, ordinary fitting plus independent prior draws, or inference with observation likelihoods disabled. Explicit score potentials remain active in prior-only inference.

TYPE: (no, yes, only) DEFAULT: "no"

num_prior_samples

Positive independent draw budget for mode "yes".

TYPE: int DEFAULT: 100

prior_seed

Isolated prior stream, independent of the inference method.

TYPE: int DEFAULT: 1

snapshot_policy

Refit-data ownership. Clone retains one independent training-data copy; reference explicitly shares later caller mutations.

TYPE: (clone, reference) DEFAULT: "clone"

RETURNS DESCRIPTION
Result

The method's result with its own type and semantics.

Source code in src/quivers/modeling/model.py
def fit[Result](
    self,
    data: Mapping[str, object],
    *,
    method: InferenceMethod[Result],
    parameters: Mapping[str, object] | None = None,
    input: torch.Tensor | None = None,
    seed: int = 0,
    sample_prior: PriorMode = "no",
    num_prior_samples: int = 100,
    prior_seed: int = 1,
    snapshot_policy: SnapshotPolicy = "clone",
) -> Result:
    """Bind external data and apply an inference method in one call.

    Parameters
    ----------
    data : Mapping[str, object]
        External values, with roles inferred from QVR.
    method : InferenceMethod[Result]
        Inference configuration, including its own random seed and budgets.
    parameters : Mapping[str, object] or None
        Static specialization arguments passed to binding.
    input : torch.Tensor or None
        One-run domain input, if the program reads one.
    seed : int
        Compilation seed, independent of the method's inference seed.
    sample_prior : {"no", "yes", "only"}
        Ordinary fitting, ordinary fitting plus independent prior draws,
        or inference with observation likelihoods disabled. Explicit score
        potentials remain active in prior-only inference.
    num_prior_samples : int
        Positive independent draw budget for mode "yes".
    prior_seed : int
        Isolated prior stream, independent of the inference method.
    snapshot_policy : {"clone", "reference"}
        Refit-data ownership. Clone retains one independent training-data
        copy; reference explicitly shares later caller mutations.

    Returns
    -------
    Result
        The method's result with its own type and semantics.
    """
    return self.bind(data, parameters=parameters, input=input, seed=seed).infer(
        method,
        sample_prior=sample_prior,
        num_prior_samples=num_prior_samples,
        prior_seed=prior_seed,
        snapshot_policy=snapshot_policy,
    )

bind

bind(data: Mapping[str, object], *, parameters: Mapping[str, object] | None = None, input: Tensor | None = None, seed: int = 0) -> BoundModel

Infer dimensions, compile, and validate one data binding.

PARAMETER DESCRIPTION
data

External data and observations. Roles and types come from QVR.

TYPE: Mapping[str, object]

parameters

Explicit static arguments. Runtime scalars belong in data.

TYPE: Mapping[str, object] or None DEFAULT: None

input

Explicit one-run domain input. Required for a real-valued domain.

TYPE: Tensor or None DEFAULT: None

seed

Compilation seed; the caller's CPU random state is restored.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
BoundModel

Compiled entry and its checked binding.

RAISES DESCRIPTION
CompileError

If sizes cannot be inferred or the source cannot be checked.

ValueError

If input names, shapes, or required values disagree with the schema.

TypeError

If supplied element types disagree with their checked types.

Source code in src/quivers/modeling/model.py
def bind(
    self,
    data: Mapping[str, object],
    *,
    parameters: Mapping[str, object] | None = None,
    input: torch.Tensor | None = None,
    seed: int = 0,
) -> BoundModel:
    """Infer dimensions, compile, and validate one data binding.

    Parameters
    ----------
    data : Mapping[str, object]
        External data and observations. Roles and types come from QVR.
    parameters : Mapping[str, object] or None
        Explicit static arguments. Runtime scalars belong in ``data``.
    input : torch.Tensor or None
        Explicit one-run domain input. Required for a real-valued domain.
    seed : int
        Compilation seed; the caller's CPU random state is restored.

    Returns
    -------
    BoundModel
        Compiled entry and its checked binding.

    Raises
    ------
    CompileError
        If sizes cannot be inferred or the source cannot be checked.
    ValueError
        If input names, shapes, or required values disagree with the schema.
    TypeError
        If supplied element types disagree with their checked types.
    """
    return self._bind(
        data,
        parameters=parameters,
        input=input,
        seed=seed,
        require_observations=True,
    )

BoundModel didactic-model

BoundModel(*, specification: Model = field(opaque=True, extras=OPAQUE_BY_IDENTITY), template_arguments: Mapping[str, object] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), compilation_seed: int, module: Program = field(opaque=True, extras=OPAQUE_BY_IDENTITY), program: MonadicProgram | CheckedProgram = field(opaque=True, extras=OPAQUE_BY_IDENTITY), schema: ModelSchema = field(opaque=True, extras=OPAQUE_BY_VALUE), data: Mapping[str, object] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), input: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

A compiled model with validated external values and one execution input.

PARAMETER DESCRIPTION
specification

Original source and entry selection, retained by identity for rebinding.

TYPE: Model DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

template_arguments

Static arguments retained by identity for recompilation.

TYPE: Mapping[str, object] DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

compilation_seed

Seed used to initialize deterministic parameters when binding.

TYPE: int

module

Compiled module container, held by identity.

TYPE: Program DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

program

Selected entry, held by identity.

TYPE: MonadicProgram or CheckedProgram DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

schema

Checked parameter and site metadata, compared by value.

TYPE: ModelSchema DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

data

External values, held by identity to preserve gradients and structured values.

TYPE: Mapping[str, object] DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

input

One run's domain input, held by identity.

TYPE: Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

rebind

rebind(data: Mapping[str, object], *, input: Tensor | None = None) -> BoundModel

Bind new data while retaining the fitted parameter interpretation.

PARAMETER DESCRIPTION
data

Replacement covariates and optional responses. Inferred dimensions specialize again; explicit cardinalities remain fixed.

TYPE: Mapping[str, object]

input

One execution input; the original input when omitted.

TYPE: Tensor or None DEFAULT: None

RETURNS DESCRIPTION
BoundModel

Independent binding with copied deterministic parameter state.

RAISES DESCRIPTION
ValueError

If the new data change latent site names or shapes.

Source code in src/quivers/modeling/model.py
def rebind(
    self, data: Mapping[str, object], *, input: torch.Tensor | None = None
) -> BoundModel:
    """Bind new data while retaining the fitted parameter interpretation.

    Parameters
    ----------
    data : Mapping[str, object]
        Replacement covariates and optional responses. Inferred dimensions
        specialize again; explicit cardinalities remain fixed.
    input : torch.Tensor or None
        One execution input; the original input when omitted.

    Returns
    -------
    BoundModel
        Independent binding with copied deterministic parameter state.

    Raises
    ------
    ValueError
        If the new data change latent site names or shapes.
    """
    rebound = self.specification._bind(
        data,
        parameters=self.template_arguments,
        input=self.input if input is None else input,
        seed=self.compilation_seed,
        require_observations=False,
    )
    original_parameters = dict(self.require_tensor_program().named_parameters())
    replacement_parameters = dict(
        rebound.require_tensor_program().named_parameters()
    )
    if original_parameters.keys() != replacement_parameters.keys():
        raise ValueError(
            "new data change deterministic parameter names; refit the model"
        )
    with torch.no_grad():
        for name, parameter in replacement_parameters.items():
            original = original_parameters[name]
            if parameter.shape != original.shape:
                raise ValueError(
                    f"new data change deterministic parameter {name!r}; refit the model"
                )
            parameter.copy_(original)

    def shapes(bound: BoundModel) -> dict[str, tuple[int, ...]]:
        observations = set(bound.schema.observations)
        recorded = bound.trace()
        return {
            name: tuple(site.value.shape)
            for name, site in recorded.sites.items()
            if not site.is_deterministic
            and name.partition("@")[0] not in observations
        }

    # Ordinary models expose their latent layout without executing a prior
    # draw. Input-dependent scans and non-bijective supports use the trace
    # fallback, which checks both bindings with the same representation.
    try:
        layouts = [
            {
                name: site.constrained_shape
                for name, site in LatentRegistry.from_model(
                    bound.require_tensor_program(),
                    set(bound.schema.observations),
                ).sites.items()
            }
            for bound in (self, rebound)
        ]
    except ValueError, NotImplementedError:
        with torch.random.fork_rng(devices=[]):
            layouts = [shapes(self), shapes(rebound)]
    if layouts[0] != layouts[1]:
        raise ValueError(
            "new data change the latent site layout; refit the model for that layout"
        )
    return rebound

infer

infer(method: InferenceMethod[Result], *, sample_prior: PriorMode = 'no', num_prior_samples: int = 100, prior_seed: int = 1, snapshot_policy: SnapshotPolicy = 'clone') -> Result

Apply a method without imposing a posterior-draw result contract.

PARAMETER DESCRIPTION
method

Solver responsible for its capability checks and result metadata.

TYPE: InferenceMethod[Result]

sample_prior

Fit the posterior, additionally retain independent priors, or disable declared observation and marginalized likelihood scores.

TYPE: (no, yes, only) DEFAULT: "no"

num_prior_samples

Positive independent prior draw budget for mode "yes".

TYPE: int DEFAULT: 100

prior_seed

Isolated CPU stream for independent prior draws.

TYPE: int DEFAULT: 1

snapshot_policy

Retained refit-data ownership for methods returning ModelFit.

TYPE: (clone, reference) DEFAULT: "clone"

RETURNS DESCRIPTION
Result

The solver's result without conversion.

RAISES DESCRIPTION
ValueError

If the policy is invalid or global score potentials prevent independent prior sampling.

TypeError

If mode "yes" is requested from a solver not returning ModelFit.

Source code in src/quivers/modeling/model.py
def infer[Result](
    self,
    method: InferenceMethod[Result],
    *,
    sample_prior: PriorMode = "no",
    num_prior_samples: int = 100,
    prior_seed: int = 1,
    snapshot_policy: SnapshotPolicy = "clone",
) -> Result:
    """Apply a method without imposing a posterior-draw result contract.

    Parameters
    ----------
    method : InferenceMethod[Result]
        Solver responsible for its capability checks and result metadata.
    sample_prior : {"no", "yes", "only"}
        Fit the posterior, additionally retain independent priors, or
        disable declared observation and marginalized likelihood scores.
    num_prior_samples : int
        Positive independent prior draw budget for mode "yes".
    prior_seed : int
        Isolated CPU stream for independent prior draws.
    snapshot_policy : {"clone", "reference"}
        Retained refit-data ownership for methods returning ModelFit.

    Returns
    -------
    Result
        The solver's result without conversion.

    Raises
    ------
    ValueError
        If the policy is invalid or global score potentials prevent
        independent prior sampling.
    TypeError
        If mode "yes" is requested from a solver not returning ModelFit.
    """
    from quivers.effects.observation_scoring import observation_scoring
    from quivers.inference.prior import _ancestral_program, _prior_mode

    mode = _prior_mode(sample_prior)
    if snapshot_policy not in {"clone", "reference"}:
        raise ValueError("snapshot_policy must be 'clone' or 'reference'")
    if mode == "yes":
        from quivers.inference._posterior import sample_count

        sample_count(num_prior_samples)
        _ancestral_program(self.require_tensor_program())
    with observation_scoring(mode != "only"):
        result = method.run(self)
    if isinstance(result, ModelFit):
        from quivers.modeling._refit import source_recipe

        prior = (
            self.prior_draws(num_samples=num_prior_samples, seed=prior_seed)
            if mode == "yes"
            else None
        )
        recipe = source_recipe(
            result.model,
            cast(InferenceMethod[ModelFit], method),
            snapshot_policy=snapshot_policy,
            sample_prior=mode,
            num_prior_samples=num_prior_samples,
            prior_seed=prior_seed,
        )
        return cast(
            Result,
            result.with_(sample_prior=mode, prior=prior, refit_recipe=recipe),
        )
    if mode == "yes":
        raise TypeError(
            "sample_prior='yes' requires an inference method returning ModelFit"
        )
    return result

prior_draws

prior_draws(*, num_samples: int = 100, seed: int = 0, method: Literal['ancestral'] | MCMC = 'ancestral') -> PriorDraws | MCMCResult

Draw retained conditional priors, or use explicit factor-conditioned MCMC.

PARAMETER DESCRIPTION
num_samples

Positive independent ancestral draw count.

TYPE: int DEFAULT: 100

seed

Isolated CPU random stream.

TYPE: int DEFAULT: 0

method

Independent sampling, or a configured driver for global potentials.

TYPE: ancestral DEFAULT: "ancestral"

RETURNS DESCRIPTION
PriorDraws or MCMCResult

Independent constrained draws or genuine factor-conditioned chains.

Source code in src/quivers/modeling/model.py
def prior_draws(
    self,
    *,
    num_samples: int = 100,
    seed: int = 0,
    method: Literal["ancestral"] | MCMC = "ancestral",
) -> PriorDraws | MCMCResult:
    """Draw retained conditional priors, or use explicit factor-conditioned MCMC.

    Parameters
    ----------
    num_samples : int
        Positive independent ancestral draw count.
    seed : int
        Isolated CPU random stream.
    method : {"ancestral"} or MCMC
        Independent sampling, or a configured driver for global potentials.

    Returns
    -------
    PriorDraws or MCMCResult
        Independent constrained draws or genuine factor-conditioned chains.
    """
    from quivers.inference.prior import prior_draws

    return prior_draws(
        self.require_tensor_program(),
        self.input,
        self.tensor_data(),
        num_samples=num_samples,
        seed=seed,
        method=method,
    )

sample

sample(sampler: MCMC) -> ModelFit

Fit using a configured MCMC driver, including its budgets and hooks.

PARAMETER DESCRIPTION
sampler

Driver with kernel, chains, seed, adaptation, and optional checkpoint.

TYPE: MCMC

RETURNS DESCRIPTION
ModelFit

Bound model and posterior draws.

RAISES DESCRIPTION
TypeError

If the selected entry cannot use the tensor inference runtime.

Source code in src/quivers/modeling/model.py
def sample(self, sampler: MCMC) -> ModelFit:
    """Fit using a configured MCMC driver, including its budgets and hooks.

    Parameters
    ----------
    sampler : MCMC
        Driver with kernel, chains, seed, adaptation, and optional checkpoint.

    Returns
    -------
    ModelFit
        Bound model and posterior draws.

    Raises
    ------
    TypeError
        If the selected entry cannot use the tensor inference runtime.
    """
    program = self.require_tensor_program()
    posterior = sampler.run(program, self.input, self.tensor_data())
    return ModelFit(model=self, posterior=posterior)

tensor_data

tensor_data() -> dict[str, Tensor]

Adapt external values to the native tensor executor's one-run layout.

Scanned observations acquire a leading run axis through tensor views. The stored binding retains its checked shapes and original objects.

RETURNS DESCRIPTION
dict[str, Tensor]

Values for a custom tensor inference method or guide constructor.

RAISES DESCRIPTION
TypeError

If the entry requires reference execution or an input has no tensor form.

Source code in src/quivers/modeling/model.py
def tensor_data(self) -> dict[str, torch.Tensor]:
    """Adapt external values to the native tensor executor's one-run layout.

    Scanned observations acquire a leading run axis through tensor views.
    The stored binding retains its checked shapes and original objects.

    Returns
    -------
    dict[str, torch.Tensor]
        Values for a custom tensor inference method or guide constructor.

    Raises
    ------
    TypeError
        If the entry requires reference execution or an input has no tensor form.
    """
    repeated = scanned_sites(self.require_tensor_program())
    values = {name: torch.as_tensor(value) for name, value in self.data.items()}
    for name in set(self.schema.observations) & repeated:
        values[name] = values[name].unsqueeze(0)
    return values

require_tensor_program

require_tensor_program() -> MonadicProgram

Select the tensor runtime or explain its current capability limit.

RETURNS DESCRIPTION
MonadicProgram

Tensor-executable program.

RAISES DESCRIPTION
TypeError

If only reference execution is available (enhancement #232).

Source code in src/quivers/modeling/model.py
def require_tensor_program(self) -> MonadicProgram:
    """Select the tensor runtime or explain its current capability limit.

    Returns
    -------
    MonadicProgram
        Tensor-executable program.

    Raises
    ------
    TypeError
        If only reference execution is available (enhancement #232).
    """
    if not isinstance(self.program, MonadicProgram):
        raise TypeError(
            "this checked entry cannot use tensor inference yet; see enhancement #232"
        )
    return self.program

trace

trace(sites: Mapping[str, Tensor] | None = None) -> Trace

Trace one run with optional latent-site conditioning.

PARAMETER DESCRIPTION
sites

Latent values to condition on; external data come from the binding. A scanned position can be addressed as name@position.

TYPE: Mapping[str, Tensor] or None DEFAULT: None

RETURNS DESCRIPTION
Trace

The execution trace, including differentiable scores.

RAISES DESCRIPTION
ValueError

If conditioning names an external input or an unknown sample site.

Source code in src/quivers/modeling/model.py
def trace(self, sites: Mapping[str, torch.Tensor] | None = None) -> Trace:
    """Trace one run with optional latent-site conditioning.

    Parameters
    ----------
    sites : Mapping[str, torch.Tensor] or None
        Latent values to condition on; external data come from the binding.
        A scanned position can be addressed as ``name@position``.

    Returns
    -------
    Trace
        The execution trace, including differentiable scores.

    Raises
    ------
    ValueError
        If conditioning names an external input or an unknown sample site.
    """
    supplied = {} if sites is None else dict(sites)
    program = self.require_tensor_program()
    repeated = scanned_sites(program)
    allowed = (set(once_sites(program)) | repeated) - set(self.schema.observations)
    unknown = set()
    for name in supplied:
        base, at, occurrence = name.rpartition("@")
        if name not in allowed and not (
            at and occurrence.isdigit() and base in allowed and base in repeated
        ):
            unknown.add(name)
    if unknown:
        raise ValueError(f"unknown latent sites: {sorted(unknown)}")
    return trace(program, self.input, {**self.tensor_data(), **supplied})

ModelFit didactic-model

ModelFit(*, model: BoundModel = field(opaque=True, extras=OPAQUE_BY_IDENTITY), posterior: MCMCResult | PriorDraws | Guide = field(opaque=True, extras=OPAQUE_BY_IDENTITY), sample_prior: PriorMode = 'no', prior: PriorDraws | MCMCResult | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), losses: tuple[float, ...] = (), refit_recipe: RefitRecipe[Mapping[str, object], InferenceMethod[ModelFit], ModelFit] | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

A bound model and fitted posterior, held by identity.

PARAMETER DESCRIPTION
model

Data, checked schema, and compiled model used by this fit.

TYPE: BoundModel DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

posterior

Genuine MCMC chains, independent prior draws, or a variational guide. Live posterior objects are held by identity.

TYPE: MCMCResult or PriorDraws or Guide DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

sample_prior

Observation-scoring and retained-prior policy used for this fit.

TYPE: (no, yes, only) DEFAULT: "no"

prior

Retained independent priors or explicitly factor-conditioned chains.

TYPE: PriorDraws or MCMCResult or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY)

losses

Optimization losses for a variational fit; empty for MCMC.

TYPE: tuple[float, ...] DEFAULT: ()

refit_recipe

Live fitting adapter and explicit training-data snapshot. Attached by BoundModel.infer; manually constructed results may omit it.

TYPE: RefitRecipe or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY)

samples property

samples: dict[str, Tensor]

Constrained draws with separate chain and draw axes.

RETURNS DESCRIPTION
dict[str, Tensor]

Recorded MCMC chains by latent site.

RAISES DESCRIPTION
TypeError

If the posterior is variational and has no recorded chains.

update

update(data: Mapping[str, object] | None = None, *, method: InferenceMethod[ModelFit] | None = None, seed: int | None = None) -> ModelFit

Refit retained or replacement data without changing this posterior.

PARAMETER DESCRIPTION
data

Replacement training data, or the recipe's retained snapshot.

TYPE: Mapping[str, object] or None DEFAULT: None

method

Explicit inference override, otherwise the retained method and seed.

TYPE: InferenceMethod[ModelFit] or None DEFAULT: None

seed

Compilation seed override. Inference seeds belong to the method.

TYPE: int or None DEFAULT: None

RETURNS DESCRIPTION
ModelFit

Fresh fitting result with the same source, entry, static arguments, domain input, and prior-scoring policy. New latent dimensions are permitted in a refit; prediction rebind remains stricter.

RAISES DESCRIPTION
ValueError

If this manually constructed result has no retained recipe.

Source code in src/quivers/modeling/model.py
def update(
    self,
    data: Mapping[str, object] | None = None,
    *,
    method: InferenceMethod[ModelFit] | None = None,
    seed: int | None = None,
) -> ModelFit:
    """Refit retained or replacement data without changing this posterior.

    Parameters
    ----------
    data : Mapping[str, object] or None
        Replacement training data, or the recipe's retained snapshot.
    method : InferenceMethod[ModelFit] or None
        Explicit inference override, otherwise the retained method and seed.
    seed : int or None
        Compilation seed override. Inference seeds belong to the method.

    Returns
    -------
    ModelFit
        Fresh fitting result with the same source, entry, static arguments,
        domain input, and prior-scoring policy. New latent dimensions are
        permitted in a refit; prediction rebind remains stricter.

    Raises
    ------
    ValueError
        If this manually constructed result has no retained recipe.
    """
    if self.refit_recipe is None:
        raise ValueError(
            "this fit has no retained refit recipe; fit through Model.fit or BoundModel.infer"
        )
    return self.refit_recipe.run(data, method=method, seed=seed)

refit_callback

refit_callback(*, method_factory: Callable[[InferenceMethod[ModelFit], int], InferenceMethod[ModelFit]], row_axis: str | None = None, partition: Callable[[Mapping[str, object], tuple[int, ...]], Mapping[str, object]] | None = None, num_samples: int | None = None) -> Callable[[FoldSplit], FoldPrediction]

Build an adapter for the shared explicit cross-validation runner.

PARAMETER DESCRIPTION
method_factory

Explicit fold-specific inference configuration. The seed comes from FoldSplit; return the method unchanged to retain its seed.

TYPE: Callable[[InferenceMethod, int], InferenceMethod]

row_axis

Checked leading nominal axis to partition. Unrelated equal-size inputs remain constants. Supply this or an explicit partitioner.

TYPE: str or None DEFAULT: None

partition

Custom row selection when a single leading axis is insufficient.

TYPE: Callable[[Mapping[str, object], tuple[int, ...]], Mapping[str, object]] or None DEFAULT: None

num_samples

Per-chain draw budget passed to existing raw held-out scoring.

TYPE: int or None DEFAULT: None

RETURNS DESCRIPTION
Callable[[FoldSplit], FoldPrediction]

Fresh fitting and raw held-out scoring, preserving actual results.

RAISES DESCRIPTION
ValueError

If the recipe or a unique partition policy is missing.

Source code in src/quivers/modeling/model.py
def refit_callback(
    self,
    *,
    method_factory: Callable[
        [InferenceMethod[ModelFit], int], InferenceMethod[ModelFit]
    ],
    row_axis: str | None = None,
    partition: Callable[
        [Mapping[str, object], tuple[int, ...]], Mapping[str, object]
    ]
    | None = None,
    num_samples: int | None = None,
) -> Callable[[FoldSplit], FoldPrediction]:
    """Build an adapter for the shared explicit cross-validation runner.

    Parameters
    ----------
    method_factory : Callable[[InferenceMethod, int], InferenceMethod]
        Explicit fold-specific inference configuration. The seed comes
        from FoldSplit; return the method unchanged to retain its seed.
    row_axis : str or None
        Checked leading nominal axis to partition. Unrelated equal-size
        inputs remain constants. Supply this or an explicit partitioner.
    partition : Callable[[Mapping[str, object], tuple[int, ...]], Mapping[str, object]] or None
        Custom row selection when a single leading axis is insufficient.
    num_samples : int or None
        Per-chain draw budget passed to existing raw held-out scoring.

    Returns
    -------
    Callable[[FoldSplit], FoldPrediction]
        Fresh fitting and raw held-out scoring, preserving actual results.

    Raises
    ------
    ValueError
        If the recipe or a unique partition policy is missing.
    """
    from quivers.modeling._refit import partition_rows
    from quivers.modeling.refit import refit_callback

    if self.refit_recipe is None:
        raise ValueError("this fit has no retained refit recipe")
    if (row_axis is None) == (partition is None):
        raise ValueError("supply exactly one row_axis or explicit partition")
    partitioner = partition
    if partitioner is None:
        assert row_axis is not None
        axis = row_axis

        def select_rows(
            data: Mapping[str, object], rows: tuple[int, ...]
        ) -> Mapping[str, object]:
            return partition_rows(self.model, data, rows, axis)

        partitioner = select_rows

    return refit_callback(
        self.refit_recipe,
        partitioner,
        lambda fitted, data, seed: fitted.log_likelihood(
            data, num_samples=num_samples, seed=seed
        ),
        method_factory=method_factory,
    )

posterior_epred

posterior_epred(data: Mapping[str, object] | None = None, *, input: Tensor | None = None, sites: Sequence[str] | None = None, num_samples: int | None = None, mc_samples: int | None = None, seed: int = 0) -> dict[str, Tensor]

Read native conditional response expectations at retained joint draws.

PARAMETER DESCRIPTION
data

New checked predictors and optional conditioning responses; None retains the original fitted binding.

TYPE: Mapping[str, object] or None DEFAULT: None

input

One-run execution input; the fitted input by default.

TYPE: Tensor or None DEFAULT: None

sites

Response names, or None for all declared observations. Exact Scan occurrence labels are supported by the generic collector.

TYPE: Sequence[str] or None DEFAULT: None

num_samples

Leading draws per recorded chain, or fresh variational draw count.

TYPE: int or None DEFAULT: None

mc_samples

Explicit approximation budget for certified finite response means without an analytic expression.

TYPE: int or None DEFAULT: None

seed

Isolated posterior and response seed; caller RNG is restored.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
dict[str, Tensor]

Conditional means preserving chain/draw/checked observation axes. Categorical and ordinal responses append a probability axis. Upstream observed and lexical values retain their conditioning; this is not an analytic joint integration over other responses.

RAISES DESCRIPTION
(ValueError, TypeError)

If binding, latent geometry, selected sites, or response moments violate the existing checked prediction contract.

Source code in src/quivers/modeling/model.py
def posterior_epred(
    self,
    data: Mapping[str, object] | None = None,
    *,
    input: torch.Tensor | None = None,
    sites: Sequence[str] | None = None,
    num_samples: int | None = None,
    mc_samples: int | None = None,
    seed: int = 0,
) -> dict[str, torch.Tensor]:
    """Read native conditional response expectations at retained joint draws.

    Parameters
    ----------
    data : Mapping[str, object] or None
        New checked predictors and optional conditioning responses;
        None retains the original fitted binding.
    input : torch.Tensor or None
        One-run execution input; the fitted input by default.
    sites : Sequence[str] or None
        Response names, or None for all declared observations. Exact Scan
        occurrence labels are supported by the generic collector.
    num_samples : int or None
        Leading draws per recorded chain, or fresh variational draw count.
    mc_samples : int or None
        Explicit approximation budget for certified finite response means
        without an analytic expression.
    seed : int
        Isolated posterior and response seed; caller RNG is restored.

    Returns
    -------
    dict[str, torch.Tensor]
        Conditional means preserving chain/draw/checked observation axes.
        Categorical and ordinal responses append a probability axis.
        Upstream observed and lexical values retain their conditioning;
        this is not an analytic joint integration over other responses.

    Raises
    ------
    ValueError, TypeError
        If binding, latent geometry, selected sites, or response moments
        violate the existing checked prediction contract.
    """
    from quivers.inference.predictive import posterior_expectations

    bound = (
        self.model
        if data is None and input is None
        else self.model.rebind(
            self.model.data if data is None else data, input=input
        )
    )
    return posterior_expectations(
        bound.require_tensor_program(),
        self.posterior,
        bound.input,
        bound.tensor_data(),
        sites=tuple(
            site.name for site in bound.schema.entry.sites if site.kind == "observe"
        )
        or bound.schema.observations
        if sites is None
        else sites,
        num_samples=num_samples,
        mc_samples=mc_samples,
        seed=seed,
    )

conditional_effects

conditional_effects(grid: PredictionGrid, *, site: str | None = None, num_samples: int | None = None, mc_samples: int | None = None, seed: int = 0) -> ConditionalEffects

Evaluate expected source responses on one checked predictor grid.

PARAMETER DESCRIPTION
grid

Explicit row-axis effect and conditioning coordinates.

TYPE: PredictionGrid

site

Declared observation; may be omitted when exactly one exists.

TYPE: str or None DEFAULT: None

num_samples

Leading draws per recorded chain or fresh variational draw count.

TYPE: int or None DEFAULT: None

mc_samples

Explicit finite-moment approximation budget when required.

TYPE: int or None DEFAULT: None

seed

Isolated posterior and response random stream.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
ConditionalEffects

Joint expected responses with explicit conditional or empirical reduction. Source grouping inputs remain checked numeric maps; the fitted latent-layout guard prevents accidental new identities.

RAISES DESCRIPTION
(ValueError, TypeError)

If observation selection, row-axis identity, conditioning data, latent layout, or response moments are invalid.

Source code in src/quivers/modeling/model.py
def conditional_effects(
    self,
    grid: PredictionGrid,
    *,
    site: str | None = None,
    num_samples: int | None = None,
    mc_samples: int | None = None,
    seed: int = 0,
) -> ConditionalEffects:
    """Evaluate expected source responses on one checked predictor grid.

    Parameters
    ----------
    grid : PredictionGrid
        Explicit row-axis effect and conditioning coordinates.
    site : str or None
        Declared observation; may be omitted when exactly one exists.
    num_samples : int or None
        Leading draws per recorded chain or fresh variational draw count.
    mc_samples : int or None
        Explicit finite-moment approximation budget when required.
    seed : int
        Isolated posterior and response random stream.

    Returns
    -------
    ConditionalEffects
        Joint expected responses with explicit conditional or empirical
        reduction. Source grouping inputs remain checked numeric maps;
        the fitted latent-layout guard prevents accidental new identities.

    Raises
    ------
    ValueError, TypeError
        If observation selection, row-axis identity, conditioning data,
        latent layout, or response moments are invalid.
    """
    from quivers.modeling._prediction import grid_data

    if site is None:
        observations = tuple(
            site.name
            for site in self.model.schema.entry.sites
            if site.kind == "observe"
        )
        if len(observations) != 1:
            raise ValueError(
                "select site explicitly when the model has multiple observations"
            )
        site = observations[0]
    data = grid_data(self.model, grid, site)
    predictions = self.posterior_epred(
        data,
        sites=(site,),
        num_samples=num_samples,
        mc_samples=mc_samples,
        seed=seed,
    )[site]
    return grid.result(
        predictions,
        kind=draw_provenance(self.posterior),
    )

evidence

evidence(sampler: SMC) -> SMCResult

Estimate the fitted target's normalizing constant with existing SMC.

PARAMETER DESCRIPTION
sampler

Configured likelihood-tempered driver, including its particle budget, rejuvenation kernel, and random stream.

TYPE: SMC

RETURNS DESCRIPTION
SMCResult

Independent particles and the estimated log normalizing constant. This is ordinary data evidence only for a normalized prior and likelihood. Observation weights instead define a powered target.

RAISES DESCRIPTION
TypeError

If the retained program has no tensor executor.

ValueError

If SMC cannot partition the target, normalize its prior, or use an exact likelihood without observation subsampling.

RuntimeError

If no temperature step meets the driver's ESS requirement.

Notes

The retained program, input, and data are reused. The fitted posterior is neither sampled nor modified; the driver's own guards and random stream govern this separate computation.

Source code in src/quivers/modeling/model.py
def evidence(self, sampler: SMC) -> SMCResult:
    """Estimate the fitted target's normalizing constant with existing SMC.

    Parameters
    ----------
    sampler : SMC
        Configured likelihood-tempered driver, including its particle
        budget, rejuvenation kernel, and random stream.

    Returns
    -------
    SMCResult
        Independent particles and the estimated log normalizing constant.
        This is ordinary data evidence only for a normalized prior and
        likelihood. Observation weights instead define a powered target.

    Raises
    ------
    TypeError
        If the retained program has no tensor executor.
    ValueError
        If SMC cannot partition the target, normalize its prior, or use
        an exact likelihood without observation subsampling.
    RuntimeError
        If no temperature step meets the driver's ESS requirement.

    Notes
    -----
    The retained program, input, and data are reused. The fitted posterior
    is neither sampled nor modified; the driver's own guards and random
    stream govern this separate computation.
    """
    return sampler.run(
        self.model.require_tensor_program(),
        self.model.input,
        self.model.tensor_data(),
    )

draws

draws(*, num_samples: int | None = None, seed: int | None = None) -> dict[str, Tensor]

Draw a variational posterior, or return recorded MCMC chains.

PARAMETER DESCRIPTION
num_samples

Maximum draws per recorded chain, or fresh guide draws. Omission retains all MCMC draws or samples 100 guide draws.

TYPE: int or None DEFAULT: None

seed

Optional CPU seed for guide sampling, restored on exit.

TYPE: int or None DEFAULT: None

RETURNS DESCRIPTION
dict[str, Tensor]

Draws with leading chain and draw axes. Variational samples have one pseudo-chain; it cannot diagnose MCMC convergence.

RAISES DESCRIPTION
ValueError

If num_samples is not positive.

Source code in src/quivers/modeling/model.py
def draws(
    self, *, num_samples: int | None = None, seed: int | None = None
) -> dict[str, torch.Tensor]:
    """Draw a variational posterior, or return recorded MCMC chains.

    Parameters
    ----------
    num_samples : int or None
        Maximum draws per recorded chain, or fresh guide draws. Omission
        retains all MCMC draws or samples 100 guide draws.
    seed : int or None
        Optional CPU seed for guide sampling, restored on exit.

    Returns
    -------
    dict[str, torch.Tensor]
        Draws with leading chain and draw axes. Variational samples have
        one pseudo-chain; it cannot diagnose MCMC convergence.

    Raises
    ------
    ValueError
        If num_samples is not positive.
    """
    from quivers.inference._posterior import constrained_draws

    return constrained_draws(
        self.posterior,
        self.model.input,
        num_samples=num_samples,
        seed=seed,
    )

prior_view

prior_view(*, num_samples: int | None = None, seed: int = 0, method: Literal['ancestral'] | MCMC = 'ancestral') -> ModelFit

Reuse prediction and analysis with retained or newly sampled prior draws.

PARAMETER DESCRIPTION
num_samples

Fresh independent count, or None to reuse retained priors. Without retained draws, None generates 100 independent draws.

TYPE: int or None DEFAULT: None

seed

Isolated CPU stream for fresh ancestral samples.

TYPE: int DEFAULT: 0

method

Conditional sampling or explicit factor-conditioned inference.

TYPE: ancestral DEFAULT: "ancestral"

RETURNS DESCRIPTION
ModelFit

A view sharing the bound model and its original priors.

Source code in src/quivers/modeling/model.py
def prior_view(
    self,
    *,
    num_samples: int | None = None,
    seed: int = 0,
    method: Literal["ancestral"] | MCMC = "ancestral",
) -> ModelFit:
    """Reuse prediction and analysis with retained or newly sampled prior draws.

    Parameters
    ----------
    num_samples : int or None
        Fresh independent count, or None to reuse retained priors. Without
        retained draws, None generates 100 independent draws.
    seed : int
        Isolated CPU stream for fresh ancestral samples.
    method : {"ancestral"} or MCMC
        Conditional sampling or explicit factor-conditioned inference.

    Returns
    -------
    ModelFit
        A view sharing the bound model and its original priors.
    """
    prior = self.prior
    if prior is None or num_samples is not None or method != "ancestral":
        prior = self.model.prior_draws(
            num_samples=100 if num_samples is None else num_samples,
            seed=seed,
            method=method,
        )
    return self.with_(posterior=prior, sample_prior="only", prior=prior, losses=())

predict

predict(data: Mapping[str, object] | None = None, *, input: Tensor | None = None, num_samples: int | None = None, seed: int | None = None) -> dict[str, Tensor]

Sample responses at the fitted data or a compatible new binding.

PARAMETER DESCRIPTION
data

New covariates and optional responses; fitted data when omitted. Observation values are released before predictive sampling.

TYPE: Mapping[str, object] or None DEFAULT: None

input

Execution input for new data; the fitted input when omitted.

TYPE: Tensor or None DEFAULT: None

num_samples

Maximum posterior draws; all available MCMC draws when omitted.

TYPE: int or None DEFAULT: None

seed

Optional CPU random seed, restored on exit.

TYPE: int or None DEFAULT: None

RETURNS DESCRIPTION
dict[str, Tensor]

Predictive samples by site at the requested data layout.

RAISES DESCRIPTION
ValueError

If new data change the latent parameter layout.

Source code in src/quivers/modeling/model.py
def predict(
    self,
    data: Mapping[str, object] | None = None,
    *,
    input: torch.Tensor | None = None,
    num_samples: int | None = None,
    seed: int | None = None,
) -> dict[str, torch.Tensor]:
    """Sample responses at the fitted data or a compatible new binding.

    Parameters
    ----------
    data : Mapping[str, object] or None
        New covariates and optional responses; fitted data when omitted.
        Observation values are released before predictive sampling.
    input : torch.Tensor or None
        Execution input for new data; the fitted input when omitted.
    num_samples : int or None
        Maximum posterior draws; all available MCMC draws when omitted.
    seed : int or None
        Optional CPU random seed, restored on exit.

    Returns
    -------
    dict[str, torch.Tensor]
        Predictive samples by site at the requested data layout.

    Raises
    ------
    ValueError
        If new data change the latent parameter layout.
    """
    context = (
        torch.random.fork_rng(devices=[]) if seed is not None else nullcontext()
    )
    with context:
        if seed is not None:
            torch.random.default_generator.manual_seed(seed)
        bound = (
            self.model
            if data is None and input is None
            else self.model.rebind(
                self.model.data if data is None else data, input=input
            )
        )
        covariates = {
            name: value
            for name, value in bound.tensor_data().items()
            if name not in bound.schema.observations
        }
        predictive = Predictive(
            bound.require_tensor_program(), self.posterior, num_samples=num_samples
        )
        predicted = predictive(bound.input, observations=covariates)
        for name in bound.schema.observations:
            if name not in predicted:
                continue
            split = tensor_shape(bound.schema.types[name])
            dimensions = () if split is None else split[1]
            if all(
                isinstance(dimension, IndexLiteral)
                and isinstance(dimension.value, int)
                for dimension in dimensions
            ):
                shape = tuple(dimension.value for dimension in dimensions)
                predicted[name] = predicted[name].reshape(
                    predicted[name].shape[0], *shape
                )
        return predicted

log_likelihood

log_likelihood(data: Mapping[str, object] | None = None, *, num_samples: int | None = None, seed: int | None = None) -> dict[str, Tensor]

Evaluate observation densities separately at posterior draws.

PARAMETER DESCRIPTION
data

Replacement covariates and observed responses; fitted data by default.

TYPE: Mapping[str, object] or None DEFAULT: None

num_samples

Maximum draws per MCMC chain; 100 draws for a guide when omitted.

TYPE: int or None DEFAULT: None

seed

Optional seed for variational draws and participating native streams, restored on exit.

TYPE: int or None DEFAULT: None

RETURNS DESCRIPTION
dict[str, Tensor]

Raw observation log densities with leading chain and draw axes. Event dimensions are reduced; observation plate axes are retained.

RAISES DESCRIPTION
ValueError

If responses are missing or the draw count is not positive.

TypeError

If an observation is hidden by marginalization and requires a marginal-likelihood observer rather than a conditional site score.

Source code in src/quivers/modeling/model.py
def log_likelihood(
    self,
    data: Mapping[str, object] | None = None,
    *,
    num_samples: int | None = None,
    seed: int | None = None,
) -> dict[str, torch.Tensor]:
    """Evaluate observation densities separately at posterior draws.

    Parameters
    ----------
    data : Mapping[str, object] or None
        Replacement covariates and observed responses; fitted data by default.
    num_samples : int or None
        Maximum draws per MCMC chain; 100 draws for a guide when omitted.
    seed : int or None
        Optional seed for variational draws and participating native streams, restored on exit.

    Returns
    -------
    dict[str, torch.Tensor]
        Raw observation log densities with leading chain and draw axes.
        Event dimensions are reduced; observation plate axes are retained.

    Raises
    ------
    ValueError
        If responses are missing or the draw count is not positive.
    TypeError
        If an observation is hidden by marginalization and requires a
        marginal-likelihood observer rather than a conditional site score.
    """
    from quivers.modeling._replay import source_analysis

    bound = self.model if data is None else self.model.rebind(data)
    return dict(
        source_analysis(
            bound, self.posterior, num_samples=num_samples, seed=seed
        ).log_likelihood
    )

analysis

analysis(*, num_samples: int | None = None, seed: int = 0) -> PosteriorAnalysis

Prepare reusable tensor posterior analysis on the fitted data.

PARAMETER DESCRIPTION
num_samples

Maximum recorded draws per chain, or fresh variational draws.

TYPE: int or None DEFAULT: None

seed

Guide sampling seed; participating caller RNG streams are preserved.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
PosteriorAnalysis

Posterior draws, raw observation scores, observed responses, and recorded sampler statistics on their original axes.

RAISES DESCRIPTION
TypeError

If a hidden observation needs a marginal-likelihood observer.

ValueError

If fitted response data are missing or the draw count is invalid.

Source code in src/quivers/modeling/model.py
def analysis(
    self, *, num_samples: int | None = None, seed: int = 0
) -> PosteriorAnalysis:
    """Prepare reusable tensor posterior analysis on the fitted data.

    Parameters
    ----------
    num_samples : int or None
        Maximum recorded draws per chain, or fresh variational draws.
    seed : int
        Guide sampling seed; participating caller RNG streams are preserved.

    Returns
    -------
    quivers.diagnostics.PosteriorAnalysis
        Posterior draws, raw observation scores, observed responses,
        and recorded sampler statistics on their original axes.

    Raises
    ------
    TypeError
        If a hidden observation needs a marginal-likelihood observer.
    ValueError
        If fitted response data are missing or the draw count is invalid.
    """
    from quivers.modeling._replay import source_analysis

    return source_analysis(
        self.model, self.posterior, num_samples=num_samples, seed=seed
    )

summary

summary() -> dict[str, ConvergenceSummary]

Summarize MCMC chains with the package's convergence estimators.

RETURNS DESCRIPTION
dict[str, ConvergenceSummary]

Means, quantiles, R-hat, ESS, and Monte Carlo errors by site.

RAISES DESCRIPTION
TypeError

If this is a variational fit, which has no MCMC chains.

Source code in src/quivers/modeling/model.py
def summary(self) -> dict[str, ConvergenceSummary]:
    """Summarize MCMC chains with the package's convergence estimators.

    Returns
    -------
    dict[str, ConvergenceSummary]
        Means, quantiles, R-hat, ESS, and Monte Carlo errors by site.

    Raises
    ------
    TypeError
        If this is a variational fit, which has no MCMC chains.
    """
    return summary(self.samples)

methods

Reusable inference components for bound QVR models.

SourceChainWorker didactic-model

SourceChainWorker(*, source: str, entry: str, families: FamilyCatalog | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), data: Mapping[str, object] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), parameters: Mapping[str, object] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), input: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), seed: int, sampler: MCMC = field(opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

Rebuild a bound QVR model in a worker process and run some chains.

The worker recompiles the source with the binding's data, static arguments, input, and compilation seed, so it builds the program the parent sampled, then runs its assigned chains with a copy of the parent's driver.

PARAMETER DESCRIPTION
source

QVR source text.

TYPE: str

entry

Selected program.

TYPE: str

families

Native family definitions of the compilation.

TYPE: FamilyCatalog or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY)

data

External values of the binding.

TYPE: Mapping[str, object] DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

parameters

Static arguments of the binding.

TYPE: Mapping[str, object] DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

input

One-run input.

TYPE: Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

seed

Compilation seed.

TYPE: int

sampler

The parent's driver.

TYPE: MCMC DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

__call__

__call__(chains: tuple[int, ...]) -> ChainStates

Recompile the binding and run the assigned chains.

PARAMETER DESCRIPTION
chains

Chain indices.

TYPE: tuple[int, ...]

RETURNS DESCRIPTION
ChainStates

Their records.

Source code in src/quivers/modeling/methods.py
def __call__(self, chains: tuple[int, ...]) -> ChainStates:
    """Recompile the binding and run the assigned chains.

    Parameters
    ----------
    chains : tuple[int, ...]
        Chain indices.

    Returns
    -------
    ChainStates
        Their records.
    """
    bound = Model(self.source, entry=self.entry, families=self.families).bind(
        self.data, parameters=self.parameters, input=self.input, seed=self.seed
    )
    return run_chains(
        self.sampler,
        bound.require_tensor_program(),
        bound.input,
        bound.tensor_data(),
        chains,
    )

MCMCMethod didactic-model

MCMCMethod(*, sampler: MCMC = field(default_factory=lambda: MCMC(NUTSKernel(), num_warmup=500, num_samples=1000, seed=0), opaque=True, extras=OPAQUE_BY_IDENTITY), cores: int = 1)

Bases: ValueModel

Fit with a reusable MCMC driver, defaulting to seeded NUTS.

PARAMETER DESCRIPTION
sampler

Driver carrying kernel, chains, warmup, seed, budgets, and callbacks. Held by identity. The default runs four NUTS chains, with 500 warmup transitions and 1000 retained draws per chain, seeded with zero.

TYPE: MCMC DEFAULT: field(default_factory=lambda: MCMC(NUTSKernel(), num_warmup=500, num_samples=1000, seed=0), opaque=True, extras=OPAQUE_BY_IDENTITY)

cores

Worker processes for the chains (brms cores). With more than one, each worker recompiles the model from its source and binding and runs its share of the chains; the result equals the serial run.

TYPE: int DEFAULT: 1

run

run(model: BoundModel) -> ModelFit

Sample the bound model using this driver's configuration.

PARAMETER DESCRIPTION
model

Validated data binding.

TYPE: BoundModel

RETURNS DESCRIPTION
ModelFit

Posterior draws and the original data binding.

RAISES DESCRIPTION
ValueError

If cores is not a positive integer, or parallel chains are requested for a driver without a seed or with a checkpoint or callback, or for a binding that cannot be pickled.

Source code in src/quivers/modeling/methods.py
def run(self, model: BoundModel) -> ModelFit:
    """Sample the bound model using this driver's configuration.

    Parameters
    ----------
    model : BoundModel
        Validated data binding.

    Returns
    -------
    ModelFit
        Posterior draws and the original data binding.

    Raises
    ------
    ValueError
        If ``cores`` is not a positive integer, or parallel chains are
        requested for a driver without a seed or with a checkpoint or
        callback, or for a binding that cannot be pickled.
    """
    if isinstance(self.cores, bool) or self.cores < 1:
        raise ValueError("cores must be a positive integer")
    if self.cores == 1 or self.sampler.num_chains == 1:
        return model.sample(self.sampler)
    specification = model.specification
    worker = SourceChainWorker(
        source=specification.source,
        entry=specification.entry,
        families=specification.families,
        data=model.data,
        parameters=model.template_arguments,
        input=model.input,
        seed=model.compilation_seed,
        sampler=self.sampler,
    )
    posterior = parallel_chains(
        self.sampler,
        model.require_tensor_program(),
        model.input,
        model.tensor_data(),
        worker,
        self.cores,
    )
    return ModelFit(model=model, posterior=posterior)

SMCMethod didactic-model

SMCMethod(*, sampler: SMC = field(default_factory=lambda: SMC(NUTSKernel(), seed=0), opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

Apply likelihood-tempered SMC to a checked data binding.

PARAMETER DESCRIPTION
sampler

Existing driver with explicit particle, rejuvenation, adaptation, and random-stream settings, held by identity. The default uses NUTS rejuvenation, 1024 particles, and seed zero.

TYPE: SMC DEFAULT: field(default_factory=lambda: SMC(NUTSKernel(), seed=0), opaque=True, extras=OPAQUE_BY_IDENTITY)

Notes

The result retains the driver's particles, temperature ladder, weight ESS, acceptance, evaluation count, and estimated log normalizing constant. Particles are not recorded MCMC chains. A data-evidence interpretation requires the declared prior and likelihood to define that comparison.

run

run(model: BoundModel) -> SMCResult

Run the existing sampler without converting its result.

PARAMETER DESCRIPTION
model

Checked program, validated data, and one-run input.

TYPE: BoundModel

RETURNS DESCRIPTION
SMCResult

Equally weighted particles and the driver's evidence diagnostics.

RAISES DESCRIPTION
TypeError

If the entry has no tensor executor.

ValueError

If the driver cannot partition the target, normalize its prior, or use an exact likelihood without observation subsampling.

Source code in src/quivers/modeling/methods.py
def run(self, model: BoundModel) -> SMCResult:
    """Run the existing sampler without converting its result.

    Parameters
    ----------
    model : BoundModel
        Checked program, validated data, and one-run input.

    Returns
    -------
    SMCResult
        Equally weighted particles and the driver's evidence diagnostics.

    Raises
    ------
    TypeError
        If the entry has no tensor executor.
    ValueError
        If the driver cannot partition the target, normalize its prior,
        or use an exact likelihood without observation subsampling.
    """
    return self.sampler.run(
        model.require_tensor_program(), model.input, model.tensor_data()
    )

PathfinderMethod didactic-model

PathfinderMethod(*, pathfinder: Pathfinder = field(default_factory=Pathfinder, opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

Fit with single- or multi-path Pathfinder variational inference.

PARAMETER DESCRIPTION
pathfinder

Driver carrying the path count, draw counts, L-BFGS settings, initialization, and seed. The default runs CmdStan's defaults: four paths of 1000 draws resampled to 1000 draws, history size 5, and 25 draws per ELBO estimate, seeded with zero. Held by identity.

TYPE: Pathfinder DEFAULT: field(default_factory=Pathfinder, opaque=True, extras=OPAQUE_BY_IDENTITY)

run

run(model: BoundModel) -> ModelFit

Run Pathfinder on the bound model's unconstrained log joint.

PARAMETER DESCRIPTION
model

Validated data binding.

TYPE: BoundModel

RETURNS DESCRIPTION
ModelFit

Bound model and PathfinderDraws, read as independent approximate posterior draws.

RAISES DESCRIPTION
TypeError

If the entry has no tensor executor.

ValueError

If every path fails or an initial point is invalid.

Source code in src/quivers/modeling/methods.py
def run(self, model: BoundModel) -> ModelFit:
    """Run Pathfinder on the bound model's unconstrained log joint.

    Parameters
    ----------
    model : BoundModel
        Validated data binding.

    Returns
    -------
    ModelFit
        Bound model and `PathfinderDraws`, read as independent
        approximate posterior draws.

    Raises
    ------
    TypeError
        If the entry has no tensor executor.
    ValueError
        If every path fails or an initial point is invalid.
    """
    posterior = self.pathfinder.run(
        model.require_tensor_program(), model.input, model.tensor_data()
    )
    return ModelFit(model=model, posterior=posterior)

VariationalMethod didactic-model

VariationalMethod(*, num_steps: int = 1000, learning_rate: float = 0.01, seed: int = 0, guide_factory: Callable[[BoundModel], Guide] | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), objective: Objective = field(default_factory=ELBO, opaque=True, extras=OPAQUE_BY_IDENTITY), optimizer_factory: Callable[[Iterable[Tensor]], Optimizer] | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), callback: Callable[[int, float], None] | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

Optimize a guide and model using a chosen objective and optimizer.

PARAMETER DESCRIPTION
num_steps

Nonnegative optimization step budget; zero retains the initialized guide.

TYPE: int DEFAULT: 1000

learning_rate

Positive Adam learning rate, used when no optimizer factory is given.

TYPE: float DEFAULT: 0.01

seed

CPU random seed for guide construction and training; restored on exit.

TYPE: int DEFAULT: 0

guide_factory

Build a fresh guide for each fit. The default is a traced AutoNormalGuide, which includes every position of a scan. Held by identity.

TYPE: Callable[[BoundModel], Guide] or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY)

objective

Variational objective, held by identity; ELBO by default.

TYPE: Objective DEFAULT: field(default_factory=ELBO, opaque=True, extras=OPAQUE_BY_IDENTITY)

optimizer_factory

Optional optimizer constructor, held by identity. Receives unique guide and model parameters so shared modules are optimized once.

TYPE: Callable[[Iterable[Tensor]], Optimizer] or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY)

callback

Called after each step with its zero-based index and loss. Held by identity.

TYPE: Callable[[int, float], None] or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY)

run

run(model: BoundModel) -> ModelFit

Fit one variational posterior and retain its loss history.

PARAMETER DESCRIPTION
model

Validated model and data.

TYPE: BoundModel

RETURNS DESCRIPTION
ModelFit

Bound model, guide, and losses. A guide's draws are approximate; optimization does not establish posterior convergence.

RAISES DESCRIPTION
ValueError

If a budget or rate is invalid, or an objective returns a nonfinite loss.

Source code in src/quivers/modeling/methods.py
def run(self, model: BoundModel) -> ModelFit:
    """Fit one variational posterior and retain its loss history.

    Parameters
    ----------
    model : BoundModel
        Validated model and data.

    Returns
    -------
    ModelFit
        Bound model, guide, and losses. A guide's draws are approximate;
        optimization does not establish posterior convergence.

    Raises
    ------
    ValueError
        If a budget or rate is invalid, or an objective returns a nonfinite loss.
    """
    if (
        self.num_steps < 0
        or not math.isfinite(self.learning_rate)
        or self.learning_rate <= 0
    ):
        raise ValueError(
            "num_steps must be nonnegative and learning_rate must be positive and finite"
        )
    program = model.require_tensor_program()
    with torch.random.fork_rng(devices=[]):
        torch.random.default_generator.manual_seed(self.seed)
        data = model.tensor_data()
        guide = (
            self.guide_factory(model)
            if self.guide_factory is not None
            else AutoNormalGuide(
                program,
                observed_names=set(model.schema.observations),
                x=model.input,
                observations=data,
            )
        )
        optimizer = _prepare_optimizer(
            program.parameters(),
            guide.parameters(),
            learning_rate=self.learning_rate,
            factory=self.optimizer_factory,
        )
        svi = SVI(program, guide, optimizer, self.objective)
        losses = svi.run(
            model.input, data, num_steps=self.num_steps, callback=self.callback
        )
    return ModelFit(model=model, posterior=guide, losses=tuple(losses))

Retained fitting recipes

ModelFit.update runs a fresh fit through its retained RefitRecipe, with explicit data ownership and inference overrides. Its fold adapter delegates to the shared cross-validation runner. See updating and refitting for nominal row axes, data snapshots, and method seeds.

refit

Retained fitting recipes and adapters for explicit held-out partitions.

SnapshotPolicy

SnapshotPolicy = Literal['clone', 'reference']

Retain an independent data snapshot or explicitly share the caller's data.

RefitRecipe dataclass

RefitRecipe(data: Data, method: Method, operation: Callable[[Data, Method, int | None], Result], *, snapshot_policy: SnapshotPolicy = 'clone', snapshot: Callable[[Data], Data] | None = None, provenance: Mapping[str, str | int] | None = None)

An identity-held fitting operation with explicit data ownership.

This is live process state, not a portable model format. A recipe runs the supplied fitter anew; it never resumes or mutates a fitted posterior.

PARAMETER DESCRIPTION
data

Original training data. Clone mode retains one independent copy, separate from posterior draws, and returns fresh copies to callers.

TYPE: Data

method

Retained inference configuration, held by identity. Its own random seed remains unchanged unless the caller supplies another method.

TYPE: Method

operation

Existing fitting adapter. The optional seed overrides preparation; its interpretation is part of the adapter's declared contract.

TYPE: Callable[[Data, Method, int or None], Result]

snapshot_policy

Clone by default. Reference mode explicitly observes later mutations of the supplied data, and is useful when another owner freezes them.

TYPE: (clone, reference) DEFAULT: "clone"

snapshot

Optional backend-specific data copier. The default copies containers and arrays, detaching and cloning tensor data without autograd graphs.

TYPE: Callable[[Data], Data] or None DEFAULT: None

provenance

Read-only descriptive reconstruction metadata, such as source/entry and compilation seed. Callables and modules remain live objects.

TYPE: Mapping[str, str or int] or None DEFAULT: None

RAISES DESCRIPTION
ValueError

If the snapshot policy is unknown.

Source code in src/quivers/modeling/refit.py
def __init__(
    self,
    data: Data,
    method: Method,
    operation: Callable[[Data, Method, int | None], Result],
    *,
    snapshot_policy: SnapshotPolicy = "clone",
    snapshot: Callable[[Data], Data] | None = None,
    provenance: Mapping[str, str | int] | None = None,
) -> None:
    if snapshot_policy not in {"clone", "reference"}:
        raise ValueError("snapshot_policy must be 'clone' or 'reference'")
    copier = _snapshot if snapshot is None else snapshot
    object.__setattr__(self, "_snapshot", copier)
    object.__setattr__(
        self, "_data", copier(data) if snapshot_policy == "clone" else data
    )
    object.__setattr__(self, "method", method)
    object.__setattr__(self, "_operation", operation)
    object.__setattr__(self, "snapshot_policy", snapshot_policy)
    object.__setattr__(self, "provenance", MappingProxyType(dict(provenance or {})))

data property

data: Data

Return isolated training data, or the explicitly shared reference.

RETURNS DESCRIPTION
Data

A fresh snapshot in clone mode, the original object otherwise.

run

run(data: Data | None = None, *, method: Method | None = None, seed: int | None = None) -> Result

Fit retained or replacement data through the original fitting adapter.

PARAMETER DESCRIPTION
data

Replacement training data, or the retained data snapshot.

TYPE: Data or None DEFAULT: None

method

Explicit inference override; otherwise retain the original method.

TYPE: Method or None DEFAULT: None

seed

Optional preparation override; None preserves the recipe's policy.

TYPE: int or None DEFAULT: None

RETURNS DESCRIPTION
Result

A fresh result with the fitter's original result semantics.

Source code in src/quivers/modeling/refit.py
def run(
    self,
    data: Data | None = None,
    *,
    method: Method | None = None,
    seed: int | None = None,
) -> Result:
    """Fit retained or replacement data through the original fitting adapter.

    Parameters
    ----------
    data : Data or None
        Replacement training data, or the retained data snapshot.
    method : Method or None
        Explicit inference override; otherwise retain the original method.
    seed : int or None
        Optional preparation override; None preserves the recipe's policy.

    Returns
    -------
    Result
        A fresh result with the fitter's original result semantics.
    """
    return self._operation(
        self.data if data is None else data,
        self.method if method is None else method,
        seed,
    )

__reduce_ex__

__reduce_ex__(protocol: SupportsIndex) -> Never

Refuse to serialize live fitting operations and inference objects.

PARAMETER DESCRIPTION
protocol

Requested pickle protocol.

TYPE: SupportsIndex

RAISES DESCRIPTION
TypeError

Recipes require a separate durable reconstruction format.

Source code in src/quivers/modeling/refit.py
def __reduce_ex__(self, protocol: SupportsIndex) -> Never:
    """Refuse to serialize live fitting operations and inference objects.

    Parameters
    ----------
    protocol : SupportsIndex
        Requested pickle protocol.

    Raises
    ------
    TypeError
        Recipes require a separate durable reconstruction format.
    """
    raise TypeError(
        "RefitRecipe contains live fitting operations and is not a durable fitted artifact"
    )

refit_callback

refit_callback(recipe: RefitRecipe[Data, Method, Result], partition: Callable[[Data, tuple[int, ...]], Data], score: Callable[[Result, Data, int], Mapping[str, Tensor]], *, method_factory: Callable[[Method, int], Method]) -> Callable[[FoldSplit], FoldPrediction]

Adapt one recipe to the existing cross-validation runner.

PARAMETER DESCRIPTION
recipe

Retained fitting adapter and original training data.

TYPE: RefitRecipe

partition

Nonmutating row selection producing fresh partitions, preserving non-row constants and identities. The adapter snapshots original data once, rather than copying the full training data for every fold.

TYPE: Callable[[Data, tuple[int, ...]], Data]

score

Existing raw held-out likelihood accessor. Its tensors retain joint chain/draw/test-row axes; weights are not predictive replications.

TYPE: Callable[[Result, Data, int], Mapping[str, Tensor]]

method_factory

Required explicit inference seed/configuration policy for each fold. Returning the original method intentionally retains its own seed.

TYPE: Callable[[Method, int], Method]

RETURNS DESCRIPTION
Callable[[FoldSplit], FoldPrediction]

A callback for cross_validate, with actual fitted results retained. Preprocessing and inference stay in the original fitting operation.

Source code in src/quivers/modeling/refit.py
def refit_callback[Data, Method, Result](
    recipe: RefitRecipe[Data, Method, Result],
    partition: Callable[[Data, tuple[int, ...]], Data],
    score: Callable[[Result, Data, int], Mapping[str, torch.Tensor]],
    *,
    method_factory: Callable[[Method, int], Method],
) -> Callable[[FoldSplit], FoldPrediction]:
    """Adapt one recipe to the existing cross-validation runner.

    Parameters
    ----------
    recipe : RefitRecipe
        Retained fitting adapter and original training data.
    partition : Callable[[Data, tuple[int, ...]], Data]
        Nonmutating row selection producing fresh partitions, preserving
        non-row constants and identities. The adapter snapshots original data
        once, rather than copying the full training data for every fold.
    score : Callable[[Result, Data, int], Mapping[str, torch.Tensor]]
        Existing raw held-out likelihood accessor. Its tensors retain joint
        chain/draw/test-row axes; weights are not predictive replications.
    method_factory : Callable[[Method, int], Method]
        Required explicit inference seed/configuration policy for each fold.
        Returning the original method intentionally retains its own seed.

    Returns
    -------
    Callable[[FoldSplit], FoldPrediction]
        A callback for cross_validate, with actual fitted results retained.
        Preprocessing and inference stay in the original fitting operation.
    """
    original = recipe.data

    def run(split: FoldSplit) -> FoldPrediction:
        fitted = recipe.run(
            partition(original, split.train),
            method=method_factory(recipe.method, split.seed),
            seed=split.seed,
        )
        return FoldPrediction(
            log_likelihood=score(fitted, partition(original, split.test), split.seed),
            fit=fitted,
        )

    return run

Durable fitted artifacts

save_fit records a source ModelFit or formula BayesianFit as a versioned JSON specification and safe tensor checkpoint. load_fit rebuilds the checked program through the original preparation path, restores its module and posterior state, and rebuilds the retained fitting recipe. It does not optimize a model or draw replacement posterior values. For a scanned guide, strict conditioned replay recovers every reached latent address from saved values; a missing value is an error.

from pathlib import Path
from tempfile import TemporaryDirectory
import torch
from quivers.modeling import Model, VariationalMethod, load_fit, save_fit

artifact_source = """object Row:FinSet _
program regression(y:Tensor[Real]([Row])):Row->Row
    sample mu <- Normal(loc=0.0,scale=1.0)
    observe y:Row <- Normal(loc=mu,scale=1.0)
    return mu
export regression
"""
artifact_fit = Model(artifact_source).fit(
    {"y": torch.tensor([-0.5, 0.25, 1.0])},
    method=VariationalMethod(num_steps=0, seed=7),
)
with TemporaryDirectory() as artifact_directory:
    artifact_path = Path(artifact_directory) / "regression.qvrfit"
    save_fit(artifact_fit, artifact_path)
    restored_fit = load_fit(artifact_path)
    for name, value in artifact_fit.posterior.state_dict().items():
        assert torch.equal(value, restored_fit.posterior.state_dict()[name])

The checkpoint retains static arguments, typed data, compilation and method seeds, parameter and buffer dtypes, tied parameters, module modes, prior policy, and recorded chain statistics. Loaded recipes reuse update and the existing fold adapter. Saving captures values at write time. A loaded reference-owned source recipe shares the loaded binding's values. A cloned recipe retains an independent training snapshot. Neither shares memory with the original process.

Formula artifacts rebuild transforms, contrasts, category labels, nonlinear designs, group layouts, threshold constraints, and retained spline knots from one frozen preparation snapshot. They restore trained neural state separately from the original predictor state retained for future refits. Loading neither executes the predictor nor calls fit. The artifact stores numeric, Boolean, string, or categorical dataframe columns with their dtypes, levels, order, and row index; live formulae evaluators are rebuilt rather than serialized.

import pandas as pd
from pathlib import Path
from tempfile import TemporaryDirectory
import torch
from quivers.formulas import fit
from quivers.modeling import load_fit, save_fit

formula_fit = fit(
    "y ~ center(x)",
    data=pd.DataFrame({"y": [.2, .4, -.1], "x": [-1., 0., 2.]}),
    method="svi", num_steps=0, seed=7,
)
new_rows = pd.DataFrame({"x": [.5, 3.]})
with TemporaryDirectory() as formula_directory:
    formula_path = Path(formula_directory) / "regression.qvrfit"
    save_fit(formula_fit, formula_path)
    restored_formula = load_fit(formula_path)
    assert torch.equal(
        formula_fit.posterior_linpred(new_data=new_rows, num_samples=4, seed=11),
        restored_formula.posterior_linpred(new_data=new_rows, num_samples=4, seed=11),
    )

Clone-owned formula recipes share their existing training snapshot internally with the reconstruction plan. Reference-owned recipes retain one separate frozen training snapshot, since later caller mutations may change a future update without changing the fitted prediction law. This costs one retained data snapshot per fit, independent of posterior draw count.

The default Normal guide, recorded MCMC results, and retained prior draws have built-in contracts. Custom guides and external Python modules require an explicit named ArtifactFactory at both write and read time. Its decoder receives an ArtifactContext when reconstructing a guide. Factories are trusted caller code and must reconstruct without fitting or sampling. An artifact never chooses an import path or falls back to arbitrary object serialization. Custom family catalogs use the same explicit factory registration. Their checked semantic definitions are saved through the QIEC wire codec and must match the reconstructed catalog exactly. The factory key should identify a stable, versioned implementation; equality of semantic metadata does not prove that an external implementation computes the declared law.

Analysis exports retain posterior tensors and diagnostics. A fitted artifact additionally retains the checked model needed for prediction and refitting. Unsupported artifact versions, missing factories, changed latent geometry, and failed integrity checks are refused before a fit is returned.

artifact

Durable fitted models reconstructed from checked specifications and tensor state.

Artifacts contain no live program, dataframe evaluator, or executable pickle. Loading rebuilds checked source or formula preparation and restores its state; it never fits a model or draws a replacement posterior. Registered factories are explicit caller-provided reconstruction code, not imports selected by the file.

ArtifactContext dataclass

ArtifactContext(program: MonadicProgram, input: Tensor, observations: Mapping[str, Tensor])

Checked execution context supplied to an explicit reconstruction factory.

PARAMETER DESCRIPTION
program

Recompiled model with restored deterministic parameter state.

TYPE: MonadicProgram

input

Original one-run input.

TYPE: Tensor

observations

Original checked host data and response bindings.

TYPE: Mapping[str, Tensor]

ArtifactFactory dataclass

ArtifactFactory(value_type: type, encode: Callable[[object], object], decode: Callable[[object, ArtifactContext | None], object])

Explicit portable configuration for an external Python class.

PARAMETER DESCRIPTION
value_type

Exact class accepted by this factory; subclasses require registration.

TYPE: type

encode

Extract declarative configuration using supported artifact values.

TYPE: Callable[[object], object]

decode

Reconstruct the class from configuration. Guide factories receive the checked model context; ordinary option factories receive None. Factories must not fit, optimize, or sample. Module tensor state is stored separately.

TYPE: Callable[[object, ArtifactContext or None], object]

save_fit

save_fit(fitted: ModelFit | BayesianFit | MultivariateFit, path: str | Path, *, factories: Mapping[str, ArtifactFactory] | None = None) -> None

Atomically save a fitted model using JSON and safe tensor payloads.

PARAMETER DESCRIPTION
fitted

Original checked model, posterior, deterministic module state, and recipe.

TYPE: ModelFit or BayesianFit or MultivariateFit

path

Destination checkpoint. An existing file is replaced only after success.

TYPE: str or Path

factories

Explicit contracts for external modules, custom guides, or method objects. No arbitrary Python object or import path is serialized.

TYPE: Mapping[str, ArtifactFactory] or None DEFAULT: None

RAISES DESCRIPTION
(TypeError, ValueError)

If the fit or one of its configurations has no portable contract.

Source code in src/quivers/modeling/artifact.py
def save_fit(
    fitted: ModelFit | _BayesianFit | _MultivariateFit,
    path: str | Path,
    *,
    factories: Mapping[str, ArtifactFactory] | None = None,
) -> None:
    """Atomically save a fitted model using JSON and safe tensor payloads.

    Parameters
    ----------
    fitted : ModelFit or BayesianFit or MultivariateFit
        Original checked model, posterior, deterministic module state, and recipe.
    path : str or pathlib.Path
        Destination checkpoint. An existing file is replaced only after success.
    factories : Mapping[str, ArtifactFactory] or None
        Explicit contracts for external modules, custom guides, or method objects.
        No arbitrary Python object or import path is serialized.

    Raises
    ------
    TypeError, ValueError
        If the fit or one of its configurations has no portable contract.
    """
    from quivers import __version__

    if isinstance(fitted, ModelFit):
        codec = _Codec(factories)
        manifest = _source_state(fitted, codec)
    else:
        if not type(fitted).__module__.startswith("quivers.formulas."):
            raise TypeError(
                "save_fit requires a source ModelFit or formula BayesianFit"
            )
        from quivers.formulas._fit import BayesianFit
        from quivers.formulas._artifact import _formula_state

        # Joint (multivariate) formula fits share this storage format.
        from quivers.formulas._joint_fit import MultivariateFit
        from quivers.formulas._joint_artifact import joint_state

        if isinstance(fitted, MultivariateFit):
            codec = _Codec(factories, formula=True)
            manifest = joint_state(fitted, codec)
        elif not isinstance(fitted, BayesianFit):
            raise TypeError(
                "save_fit requires a source ModelFit or formula BayesianFit"
            )
        else:
            codec = _Codec(factories, formula=True)
            manifest = _formula_state(fitted, codec)
    manifest.update(
        format=_FORMAT, producer={"package": "quivers", "version": __version__}
    )
    text = json.dumps(manifest, sort_keys=True, allow_nan=False)
    payload = {
        "manifest": text,
        "manifest_sha256": hashlib.sha256(text.encode()).hexdigest(),
        "tensors": codec.tensors,
        "digests": {
            name: tensor_digest(value) for name, value in codec.tensors.items()
        },
    }
    with atomic_output(Path(path)) as temporary:
        torch.save(payload, temporary)

load_fit

load_fit(path: str | Path, *, factories: Mapping[str, ArtifactFactory] | None = None, map_location: str | device = 'cpu') -> ModelFit | BayesianFit | MultivariateFit

Reconstruct a fit without optimization or replacement posterior draws.

PARAMETER DESCRIPTION
path

Fitted artifact produced by save_fit.

TYPE: str or Path

factories

Explicit trusted reconstructors required by the artifact.

TYPE: Mapping[str, ArtifactFactory] or None DEFAULT: None

map_location

Tensor destination, passed to torch.load with weights_only=True.

TYPE: str or device DEFAULT: 'cpu'

RETURNS DESCRIPTION
ModelFit or BayesianFit or MultivariateFit

Independent checked binding, posterior, and reconstructed live recipe. Loading a reference-owned recipe shares its newly loaded data, not the original process's memory. Saving always captures values at write time.

RAISES DESCRIPTION
(ValueError, TypeError, RuntimeError)

If the format, tensor integrity, checked source, or factory contract fails.

Source code in src/quivers/modeling/artifact.py
def load_fit(
    path: str | Path,
    *,
    factories: Mapping[str, ArtifactFactory] | None = None,
    map_location: str | torch.device = "cpu",
) -> ModelFit | _BayesianFit | _MultivariateFit:
    """Reconstruct a fit without optimization or replacement posterior draws.

    Parameters
    ----------
    path : str or pathlib.Path
        Fitted artifact produced by save_fit.
    factories : Mapping[str, ArtifactFactory] or None
        Explicit trusted reconstructors required by the artifact.
    map_location : str or torch.device
        Tensor destination, passed to torch.load with weights_only=True.

    Returns
    -------
    ModelFit or BayesianFit or MultivariateFit
        Independent checked binding, posterior, and reconstructed live recipe.
        Loading a reference-owned recipe shares its newly loaded data, not the
        original process's memory. Saving always captures values at write time.

    Raises
    ------
    ValueError, TypeError, RuntimeError
        If the format, tensor integrity, checked source, or factory contract fails.
    """
    payload = torch.load(path, map_location=map_location, weights_only=True)
    if not isinstance(payload, dict) or set(payload) != {
        "manifest",
        "manifest_sha256",
        "tensors",
        "digests",
    }:
        raise ValueError("not a fitted artifact payload")
    text = payload["manifest"]
    if (
        not isinstance(text, str)
        or hashlib.sha256(text.encode()).hexdigest() != payload["manifest_sha256"]
    ):
        raise ValueError("artifact manifest integrity check failed")
    manifest = json.loads(text)
    if manifest.get("format") != _FORMAT or manifest.get("kind") not in {
        "source",
        "formula",
        "formula_joint",
    }:
        raise ValueError("unsupported fitted artifact format or kind")
    tensors, digests = payload["tensors"], payload["digests"]
    if (
        not isinstance(tensors, dict)
        or not isinstance(digests, dict)
        or set(tensors) != set(digests)
    ):
        raise ValueError("artifact tensor index is malformed")
    for name, value in tensors.items():
        if not isinstance(value, torch.Tensor) or tensor_digest(value) != digests[name]:
            raise ValueError(f"artifact tensor integrity check failed for {name!r}")
    codec = _Codec(
        factories, tensors, formula=manifest["kind"] in {"formula", "formula_joint"}
    )
    from quivers._rng import seeded_rng

    with seeded_rng(0, devices=[value.device for value in tensors.values()]):
        if manifest["kind"] == "source":
            return _restore_source(manifest, codec)
        if manifest["kind"] == "formula_joint":
            from quivers.formulas._joint_artifact import restore_joint

            return restore_joint(manifest, codec)
        from quivers.formulas._artifact import _restore_formula

        return _restore_formula(manifest, codec)

ArtifactContext dataclass

ArtifactContext(program: MonadicProgram, input: Tensor, observations: Mapping[str, Tensor])

Checked execution context supplied to an explicit reconstruction factory.

PARAMETER DESCRIPTION
program

Recompiled model with restored deterministic parameter state.

TYPE: MonadicProgram

input

Original one-run input.

TYPE: Tensor

observations

Original checked host data and response bindings.

TYPE: Mapping[str, Tensor]

ArtifactFactory dataclass

ArtifactFactory(value_type: type, encode: Callable[[object], object], decode: Callable[[object, ArtifactContext | None], object])

Explicit portable configuration for an external Python class.

PARAMETER DESCRIPTION
value_type

Exact class accepted by this factory; subclasses require registration.

TYPE: type

encode

Extract declarative configuration using supported artifact values.

TYPE: Callable[[object], object]

decode

Reconstruct the class from configuration. Guide factories receive the checked model context; ordinary option factories receive None. Factories must not fit, optimize, or sample. Module tensor state is stored separately.

TYPE: Callable[[object, ArtifactContext or None], object]