Skip to content

Refit cross-validation

A fold plan records which original rows a refit may use and which rows it must predict. fold_plan constructs reusable random, grouped, or stratified partitions; cross_validate applies an existing fitting procedure to those partitions and scores its raw held-out likelihoods. Both need only PyTorch.

The result retains (i) the complete partition and selected folds, (ii) the original rows in each predictive unit, and (iii) optional actual fitted results. This page first specifies partition and scoring semantics, then applies the same runner to QVR source and formula fits.

Partitions and predictive units

FoldPlan.assignments contains one zero-based fold per original included row. fold_plan(n, folds=k, groups=labels) keeps every group in one fold; strata=labels balances strata across folds. A grouped stratum must be constant within each indivisible group. Random tie breaking uses a local seeded stream. Construction takes linear storage and uses a heap to balance groups, avoiding work proportional to the number of folds for every row.

For leave-one-out prediction, use one fold per row. To leave out the rest of that row's group as well, set FoldPlan.omission_groups: split.test still names the one designated row, while split.omitted includes its whole group. Thus the training set and prediction unit can express different questions.

A refit returns FoldPrediction(log_likelihood=...), with unweighted response scores of shape (chain, draw, test_row) in exactly split.test order. The callback owns preprocessing, priors, basis construction, and inference quality. In particular, fit learned preprocessing on training rows and apply the retained transformation to held-out rows; splitting after fitting preprocessing may leak information. An excluded group can leave no training rows, so that callback must then support a prior fit.

joint="observation" scores each row separately. joint="fold" scores the whole held-out fold together; joint="group" and explicit groups score each group within a fold. Multiple responses require an explicit responses selection and aligned joint posterior draws. The runner sums all selected response and row log likelihoods within each draw, then computes log-mean-exp across draws. Summing marginal log predictive densities instead would describe a different prediction. The brms K-fold reference distinguishes these observation, fold, and group prediction units. The loo ELPD reference describes pointwise log-likelihood arrays with separate iteration, chain, and data axes.

fold_ids evaluates a subset without extrapolating missing folds. result.elpd sums only evaluated units; result.complete reports whether all folds ran. result.se is the descriptive square root of the number of units times their sample variance, rather than a Monte Carlo error estimate or a correction for overlapping training sets. Zero predictive densities remain -inf; an undefined SE is NaN. Compare models using the same rows, response selection, partition, and predictive units. These policies also correspond to the partition, selected fold, and joint-scoring controls in the brms K-fold interface.

QVR source refits

Each callback fits a fresh binding of the same specification. Held-out scoring uses ModelFit.log_likelihood, including its checked response semantics and retained parameters. The small budgets below demonstrate the interface; assess optimization or MCMC diagnostics before interpreting predictive comparisons.

import torch
from quivers.diagnostics import FoldPrediction, cross_validate, fold_plan
from quivers.modeling import Model, VariationalMethod

source = """object Row : FinSet _
object Out : Real 1
program regression(x : Tensor[Real]([Row]), y : Tensor[Real]([Row])) : Row -> Out
    sample b <- Normal(loc=0.0, scale=1.0)
    let mu = b * x
    observe y : Row <- Normal(loc=mu, scale=1.0)
    return b
export regression
"""
specification = Model(source)
data = {"x": torch.tensor([-1., 0., 1., 2.]),
        "y": torch.tensor([-0.7, 0.1, 0.9, 1.8])}
plan = fold_plan(4, folds=2, seed=11)

def refit(split):
    training = {name: value[list(split.train)] for name, value in data.items()}
    testing = {name: value[list(split.test)] for name, value in data.items()}
    fitted = specification.fit(
        training, method=VariationalMethod(num_steps=2, seed=split.seed),
    )
    scores = fitted.log_likelihood(testing, num_samples=4, seed=split.seed)
    return FoldPrediction(log_likelihood=scores, fit=fitted)

result = cross_validate(plan, refit, save_fits=True)
assert result.complete and result.log_predictive_density.shape == (4,)
assert set(result.fits) == {0, 1}

Prediction reuses the fitted latent layout. Row-specific latent variables whose layout changes with held-out data require an explicit marginal or new-level prediction policy; a refitter must provide those raw scores rather than silently rebinding them to unrelated latent coordinates.

Formula refits

The callback changes, while the partition and scorer remain the same. Formula fits use their existing log_likelihood(new_data=...) path, which retains response transforms, categories, and declared group prediction policies.

import pandas as pd
from quivers.diagnostics import FoldPrediction, cross_validate, fold_plan
from quivers.formulas import fit

frame = pd.DataFrame({"x": [-1., 0., 1., 2.], "y": [-0.7, 0.1, 0.9, 1.8]})
plan = fold_plan(len(frame), folds=2, seed=11)

def refit_formula(split):
    fitted = fit(
        "y ~ x", data=frame.iloc[list(split.train)],
        method="svi", num_steps=2, seed=split.seed,
    )
    scores = fitted.log_likelihood(
        new_data=frame.iloc[list(split.test)], num_samples=4, seed=split.seed,
    )
    return FoldPrediction(log_likelihood=scores)

result = cross_validate(plan, refit_formula, joint="fold")
assert result.complete and result.log_predictive_density.shape == (2,)

A new grouping level requires the fitted predictor's explicit new-level policy. The runner does not infer that policy from fold labels. Fold-specific streams are stable under fold selection and evaluation order, and participating caller RNG streams are restored after each callback. Actual fits are retained only when save_fits=True; otherwise they can be released before the next fold.

cross_validation

Explicit refit partitions and held-out posterior predictive scores.

FoldLabel

FoldLabel = str | int

A retained group or stratum label; labels are never inferred from outcomes.

FoldSplit didactic-model

FoldSplit(*, fold: int, train: tuple[int, ...], test: tuple[int, ...], omitted: tuple[int, ...], seed: int)

Bases: ValueModel

Original row identities for one refit and its held-out prediction.

PARAMETER DESCRIPTION
fold

Zero-based fold identity in the complete plan.

TYPE: int

train

Original row positions supplied to the refitting procedure.

TYPE: tuple[int, ...]

test

Original row positions to predict, in their original order.

TYPE: tuple[int, ...]

omitted

Rows excluded from training, possibly including other group members.

TYPE: tuple[int, ...]

seed

Fold-specific seed independent of evaluation order or selected folds.

TYPE: int

FoldPlan didactic-model

FoldPlan(*, assignments: tuple[int, ...], seed: int = 0, omission_groups: tuple[FoldLabel, ...] = ())

Bases: ValueModel

A reusable complete partition, independent of model and fitting backend.

PARAMETER DESCRIPTION
assignments

One zero-based fold per original included row. Every fold must occur.

TYPE: tuple[int, ...]

seed

Nonnegative seed used to derive independent refit streams.

TYPE: int DEFAULT: 0

omission_groups

Optional grouping identities. A fold also omits every member of a held-out row's group, while predicting only its designated test rows. This expresses leave-one-out prediction with whole-group exclusion.

TYPE: tuple[str or int, ...] DEFAULT: ()

num_folds property

num_folds: int

Return the number of nonempty folds.

RETURNS DESCRIPTION
int

Complete partition size.

split

split(fold: int) -> FoldSplit

Resolve training, omitted, and prediction rows for one fold.

PARAMETER DESCRIPTION
fold

Zero-based fold identity.

TYPE: int

RETURNS DESCRIPTION
FoldSplit

Original positions; an explicitly omitted whole group can make training empty, in which case the refitter must support prior fits.

RAISES DESCRIPTION
ValueError

If the requested fold is outside the complete partition.

Source code in src/quivers/diagnostics/cross_validation.py
def split(self, fold: int) -> FoldSplit:
    """Resolve training, omitted, and prediction rows for one fold.

    Parameters
    ----------
    fold : int
        Zero-based fold identity.

    Returns
    -------
    FoldSplit
        Original positions; an explicitly omitted whole group can make
        training empty, in which case the refitter must support prior fits.

    Raises
    ------
    ValueError
        If the requested fold is outside the complete partition.
    """
    if type(fold) is not int or not 0 <= fold < self.num_folds:
        raise ValueError("fold index is outside the complete partition")
    test = tuple(i for i, value in enumerate(self.assignments) if value == fold)
    if self.omission_groups:
        excluded = {self.omission_groups[i] for i in test}
        omitted = tuple(
            i for i, group in enumerate(self.omission_groups) if group in excluded
        )
    else:
        omitted = test
    omit = set(omitted)
    return FoldSplit(
        fold=fold,
        train=tuple(i for i in range(len(self.assignments)) if i not in omit),
        test=test,
        omitted=omitted,
        seed=(self.seed + fold + 1) % 2**63,
    )

FoldPrediction didactic-model

FoldPrediction(*, log_likelihood: Mapping[str, Tensor] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), fit: object | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

Raw held-out likelihoods returned by a refitting adapter.

PARAMETER DESCRIPTION
log_likelihood

Response scores of shape (chain, draw, test row), unweighted and with each response event already reduced. Joint responses share draw axes.

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

fit

Optional actual fitted result, retained only when save_fits is true.

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

CrossValidationResult didactic-model

CrossValidationResult(*, plan: FoldPlan, fold_ids: tuple[int, ...], responses: tuple[str, ...], joint: Literal['observation', 'fold', 'group'], units: tuple[tuple[int, tuple[int, ...]], ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), log_predictive_density: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), fits: Mapping[int, object] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

Predictive scores from explicit refits on a retained partition.

PARAMETER DESCRIPTION
plan

Complete original partition.

TYPE: FoldPlan

fold_ids

Evaluated folds; a subset is never extrapolated to a full result.

TYPE: tuple[int, ...]

responses

Selected response names, summed within each joint posterior draw.

TYPE: tuple[str, ...]

joint

Predictive unit: observation, whole fold, or group within fold.

TYPE: str

units

Fold identity and original response positions for every scored unit.

TYPE: tuple[tuple[int, tuple[int, ...]], ...] DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

log_predictive_density

Float64 log-mean likelihood per unit, preserving zero densities as -inf.

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

fits

Optional actual refits keyed by complete-plan fold identity.

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

complete property

complete: bool

Report whether every fold in the retained partition was evaluated.

RETURNS DESCRIPTION
bool

False for a partial fold selection, regardless of score values.

elpd property

elpd: Tensor

Sum evaluated predictive units without extrapolating missing folds.

RETURNS DESCRIPTION
Tensor

Scalar score on the natural-log scale; -inf remains -inf.

se property

se: Tensor

Return sqrt(N times sample variance) across evaluated score units.

RETURNS DESCRIPTION
Tensor

Descriptive sampling-unit SE, not a Monte Carlo SE or a correction for overlapping training folds. Undefined for fewer than two units or nonfinite scores, in which case it is NaN.

fold_plan

fold_plan(size: int, *, folds: int = 10, groups: Sequence[FoldLabel] | None = None, strata: Sequence[FoldLabel] | None = None, seed: int = 0) -> FoldPlan

Construct seeded balanced random, grouped, or stratified folds.

PARAMETER DESCRIPTION
size

Number of original included response rows.

TYPE: int

folds

Number of nonempty folds, at most the number of independent groups. Setting this to size gives leave-one-out when groups are absent.

TYPE: int DEFAULT: 10

groups

Indivisible units assigned wholly to one fold.

TYPE: Sequence[str or int] or None DEFAULT: None

strata

Labels balanced across folds. Every indivisible group must have one stratum; small strata need not occur in every fold.

TYPE: Sequence[str or int] or None DEFAULT: None

seed

Local random stream; the caller's RNG is preserved.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
FoldPlan

Original row order and exact assignments for reuse across models.

RAISES DESCRIPTION
ValueError

If counts, labels, or group/stratum combinations are invalid.

Source code in src/quivers/diagnostics/cross_validation.py
def fold_plan(
    size: int,
    *,
    folds: int = 10,
    groups: Sequence[FoldLabel] | None = None,
    strata: Sequence[FoldLabel] | None = None,
    seed: int = 0,
) -> FoldPlan:
    """Construct seeded balanced random, grouped, or stratified folds.

    Parameters
    ----------
    size : int
        Number of original included response rows.
    folds : int
        Number of nonempty folds, at most the number of independent groups.
        Setting this to size gives leave-one-out when groups are absent.
    groups : Sequence[str or int] or None
        Indivisible units assigned wholly to one fold.
    strata : Sequence[str or int] or None
        Labels balanced across folds. Every indivisible group must have one
        stratum; small strata need not occur in every fold.
    seed : int
        Local random stream; the caller's RNG is preserved.

    Returns
    -------
    FoldPlan
        Original row order and exact assignments for reuse across models.

    Raises
    ------
    ValueError
        If counts, labels, or group/stratum combinations are invalid.
    """
    if type(size) is not int or size < 2 or type(folds) is not int or folds < 2:
        raise ValueError("fold construction requires at least two rows and two folds")
    if type(seed) is not int or not 0 <= seed < 2**63:
        raise ValueError("fold seed must lie in [0, 2**63)")
    group_values = (
        tuple(range(size)) if groups is None else _labels(groups, size, "groups")
    )
    stratum_values = (0,) * size if strata is None else _labels(strata, size, "strata")
    units: dict[FoldLabel, list[int]] = {}
    for row, group in enumerate(group_values):
        units.setdefault(group, []).append(row)
    if folds > len(units):
        raise ValueError("fold count exceeds the number of indivisible groups")
    by_stratum: dict[FoldLabel, list[list[int]]] = {}
    for rows in units.values():
        stratum = stratum_values[rows[0]]
        if any(stratum_values[row] != stratum for row in rows):
            raise ValueError("each indivisible group must belong to one stratum")
        by_stratum.setdefault(stratum, []).append(rows)
    generator = torch.Generator().manual_seed(seed)
    totals = [0] * folds
    assignments = [0] * size
    priorities = torch.randperm(folds, generator=generator).tolist()
    global_heap = [(0, priorities[i], i) for i in range(folds)]
    heapq.heapify(global_heap)
    for values in by_stratum.values():
        # Shuffle equal-size units before balancing large groups first.
        order = torch.randperm(len(values), generator=generator).tolist()
        ordered = sorted((values[i] for i in order), key=len, reverse=True)
        if len(ordered) < folds:
            # Every group can occupy a distinct fold in this stratum. Holding
            # selected folds out of the heap avoids O(K) work per small stratum.
            used = []
            for rows in ordered:
                _, priority, fold = heapq.heappop(global_heap)
                totals[fold] += len(rows)
                used.append((totals[fold], priority, fold))
                for row in rows:
                    assignments[row] = fold
            for item in used:
                heapq.heappush(global_heap, item)
        else:
            local_heap = [(0, totals[i], priorities[i], i) for i in range(folds)]
            heapq.heapify(local_heap)
            for rows in ordered:
                count, _, priority, fold = heapq.heappop(local_heap)
                totals[fold] += len(rows)
                heapq.heappush(
                    local_heap, (count + len(rows), totals[fold], priority, fold)
                )
                for row in rows:
                    assignments[row] = fold
            global_heap = [(totals[i], priorities[i], i) for i in range(folds)]
            heapq.heapify(global_heap)
    return FoldPlan(assignments=tuple(assignments), seed=seed)

cross_validate

cross_validate(plan: FoldPlan, refit: Callable[[FoldSplit], FoldPrediction], *, fold_ids: Sequence[int] | None = None, responses: Sequence[str] | None = None, joint: Literal['observation', 'fold', 'group'] = 'observation', groups: Sequence[FoldLabel] | None = None, save_fits: bool = False) -> CrossValidationResult

Refit selected partitions and score held-out units within joint draws.

PARAMETER DESCRIPTION
plan

Explicit reusable partition of original included rows.

TYPE: FoldPlan

refit

Adapter that fits only split.train and scores exactly split.test. It owns preprocessing, prior/basis policy, inference quality, and raw observation semantics; the runner does not fit another model itself.

TYPE: Callable[[FoldSplit], FoldPrediction]

fold_ids

Nonempty unique subset of complete-plan folds, or all folds.

TYPE: Sequence[int] or None DEFAULT: None

responses

Explicit joint response selection; required with multiple scored names.

TYPE: Sequence[str] or None DEFAULT: None

joint

Sum row/response log likelihoods within a draw before log-mean-exp.

TYPE: ('observation', 'fold', 'group') DEFAULT: "observation"

groups

Original row labels for joint group-within-fold prediction units.

TYPE: Sequence[str or int] or None DEFAULT: None

save_fits

Retain actual callback results and their omitted-row metadata in plan.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
CrossValidationResult

Conditional predictive scores from refits, retaining exact row units. Leave-one-out partitions still have the supplied fitter's approximation.

RAISES DESCRIPTION
ValueError

If selections, response shapes, or scores are invalid or inconsistent.

TypeError

If a refitter does not return raw real floating-point likelihoods.

Source code in src/quivers/diagnostics/cross_validation.py
def cross_validate(
    plan: FoldPlan,
    refit: Callable[[FoldSplit], FoldPrediction],
    *,
    fold_ids: Sequence[int] | None = None,
    responses: Sequence[str] | None = None,
    joint: Literal["observation", "fold", "group"] = "observation",
    groups: Sequence[FoldLabel] | None = None,
    save_fits: bool = False,
) -> CrossValidationResult:
    """Refit selected partitions and score held-out units within joint draws.

    Parameters
    ----------
    plan : FoldPlan
        Explicit reusable partition of original included rows.
    refit : Callable[[FoldSplit], FoldPrediction]
        Adapter that fits only split.train and scores exactly split.test.
        It owns preprocessing, prior/basis policy, inference quality, and raw
        observation semantics; the runner does not fit another model itself.
    fold_ids : Sequence[int] or None
        Nonempty unique subset of complete-plan folds, or all folds.
    responses : Sequence[str] or None
        Explicit joint response selection; required with multiple scored names.
    joint : {"observation", "fold", "group"}
        Sum row/response log likelihoods within a draw before log-mean-exp.
    groups : Sequence[str or int] or None
        Original row labels for joint group-within-fold prediction units.
    save_fits : bool
        Retain actual callback results and their omitted-row metadata in plan.

    Returns
    -------
    CrossValidationResult
        Conditional predictive scores from refits, retaining exact row units.
        Leave-one-out partitions still have the supplied fitter's approximation.

    Raises
    ------
    ValueError
        If selections, response shapes, or scores are invalid or inconsistent.
    TypeError
        If a refitter does not return raw real floating-point likelihoods.
    """
    from quivers._rng import seeded_rng

    chosen = tuple(range(plan.num_folds)) if fold_ids is None else tuple(fold_ids)
    if not chosen or len(set(chosen)) != len(chosen):
        raise ValueError("select a nonempty set of unique fold identities")
    count = plan.num_folds
    if any(type(fold) is not int or not 0 <= fold < count for fold in chosen):
        raise ValueError("fold index is outside the complete partition")
    if joint not in {"observation", "fold", "group"} or type(save_fits) is not bool:
        raise ValueError("invalid predictive unit or save_fits policy")
    labels = (
        None
        if groups is None
        else _labels(groups, len(plan.assignments), "score groups")
    )
    if (joint == "group") != (labels is not None):
        raise ValueError("score groups must be supplied exactly when joint='group'")
    selected = None if responses is None else tuple(responses)
    if selected is not None and (
        not selected
        or len(set(selected)) != len(selected)
        or any(not isinstance(name, str) or not name for name in selected)
    ):
        raise ValueError("response selection must contain unique nonempty names")
    values: list[torch.Tensor] = []
    units: list[tuple[int, tuple[int, ...]]] = []
    fits: dict[int, object] = {}
    device: torch.device | None = None
    for fold in chosen:
        split = plan.split(fold)
        with seeded_rng(split.seed):
            prediction = refit(split)
        score, selected = _prediction_scores(prediction, split, selected, device)
        device = score.device
        positions: list[list[int]]
        if joint == "observation":
            positions = [[i] for i in range(len(split.test))]
        elif joint == "fold":
            positions = [list(range(len(split.test)))]
        else:
            assert labels is not None
            buckets: dict[FoldLabel, list[int]] = {}
            for i, original in enumerate(split.test):
                buckets.setdefault(labels[original], []).append(i)
            positions = list(buckets.values())
        # Pool sample axes only after summing each predictive unit within draw.
        per_unit = (
            score
            if joint == "observation"
            else torch.stack([score[..., rows].sum(-1) for rows in positions], -1)
        )
        pooled = per_unit.flatten(0, 1)
        values.append(torch.logsumexp(pooled, 0) - math.log(pooled.shape[0]))
        units.extend(
            (split.fold, tuple(split.test[i] for i in rows)) for rows in positions
        )
        if save_fits:
            if prediction.fit is None:
                raise ValueError(
                    "save_fits requires an actual fitted result from every refitter"
                )
            fits[split.fold] = prediction.fit
        del prediction
    assert selected is not None
    return CrossValidationResult(
        plan=plan,
        fold_ids=chosen,
        responses=selected,
        joint=joint,
        units=tuple(units),
        log_predictive_density=torch.cat(values),
        fits=fits,
    )