Skip to content

Fit cache

Fits and runs keyed by content hashes, data digests, configuration, seeds, and engine identity. Model.fit takes a cache through its cache argument.

fits

Content-addressed caching of fits and runs.

A fit is determined by the meaning of the program fitted, the data it is fitted to, the sites held fixed, the inference and runtime configuration, the seeds, and the engine that computes it. FitKey records exactly these, each as a digest:

  • the entry hash: the content hash of the checked entry point (module_hashes), which is invariant under renaming, reordering, comments, and formatting, together with the digest of the checked interpretation bindings that accompany it;
  • the entry's observable names: its site labels, the names of the parameters a run supplies by name, and returned names, which key the stored result's values. A rename of anything else (a computation, a family, a handler, a local, a domain parameter, which takes its value by position, the program itself) leaves the key unchanged and reuses the stored fit;
  • the data, one digest per program parameter, by parameter position;
  • the fixed sites, one digest per conditioned site, by site ordinal;
  • the configuration: the inference method and every option of the fit or run;
  • the seeds;
  • the engine identity: the quivers version, the kernel ABI, the content-hash format, the torch and Python versions, and the platform.

A cache hit returns the stored artifact unchanged: a fit is reloaded with load_fit from the bytes save_fit wrote, and a run returns the JSON payload it printed. Anything without a content identity (a native family implementation, a programmatic runtime provider, a method configured without a seed) is refused rather than cached, because no stored artifact could stand for it.

ExternalValue

ExternalValue = None | bool | int | float | str | Tensor | Model | ArrayLike | Sequence[ExternalValue] | Mapping[str, ExternalValue]

A value supplied to a fit or run from outside the program: a datum, a site value, a static argument, or a configuration record.

FitKind

FitKind = Literal['fit', 'run']

What a key addresses: a Model.fit result or an invoke_entry run.

ArrayLike

Bases: Protocol

A value that exposes an array view, such as a NumPy array.

__array__

__array__() -> ArrayLike

The value as an array.

RETURNS DESCRIPTION
ArrayLike

The array view.

Source code in src/quivers/modeling/model.py
def __array__(self) -> ArrayLike:
    """The value as an array.

    Returns
    -------
    ArrayLike
        The array view.
    """
    ...

FitCacheError

Bases: ValueError

A fit or run has no content identity, so it cannot be cached.

KeyedDigest didactic-model

KeyedDigest(*, position: int, digest: str)

Bases: Model

The digest of one value at one position of a key.

PARAMETER DESCRIPTION
position

A parameter position or a site ordinal.

TYPE: int

digest

The value's digest.

TYPE: str

FitKey didactic-model

FitKey(*, kind: FitKind, entry: str, companions: str, source: str, names: tuple[str, ...], data: tuple[KeyedDigest, ...], fixed_sites: tuple[KeyedDigest, ...], configuration: str, seeds: tuple[int, ...], engine: str)

Bases: Model

Everything that determines a fit or run, as digests.

PARAMETER DESCRIPTION
kind

A fit or a run.

TYPE: FitKind

entry

The content hash of the entry point.

TYPE: str

companions

The digest of the checked interpretation bindings the entry runs with, in the module's content context.

TYPE: str

source

For a fit, the digest of the program source's modules (program_source_digest), which covers what the checked core does not record; empty for a run, which the reference machine executes from the checked core alone.

TYPE: str

names

The entry's observable names, in ordinal order.

TYPE: tuple[str, ...]

data

Each supplied parameter's position with the digest of its value.

TYPE: tuple[KeyedDigest, ...]

fixed_sites

Each conditioned site's ordinal among names with the digest of its value.

TYPE: tuple[KeyedDigest, ...]

configuration

The digest of the inference method and the options of the fit or run.

TYPE: str

seeds

The seeds.

TYPE: tuple[int, ...]

engine

The digest of the engine identity.

TYPE: str

digest

digest() -> str

The store key of the fit or run.

RETURNS DESCRIPTION
str

The digest of every component.

Source code in src/quivers/incremental/fits.py
def digest(self) -> str:
    """The store key of the fit or run.

    Returns
    -------
    str
        The digest of every component.
    """
    return tagged_digest(
        "fit-key",
        [
            self.kind,
            self.entry,
            self.companions,
            self.source,
            list(self.names),
            [[item.position, item.digest] for item in self.data],
            [[item.position, item.digest] for item in self.fixed_sites],
            self.configuration,
            list(self.seeds),
            self.engine,
        ],
    )

FitCacheEvent didactic-model

FitCacheEvent(*, kind: FitKind, key: str, hit: bool)

Bases: Model

One lookup of a cache.

PARAMETER DESCRIPTION
kind

A fit or a run.

TYPE: FitKind

key

The key's digest.

TYPE: str

hit

Whether the stored artifact was returned.

TYPE: bool

CachedRun didactic-model

CachedRun(*, key: str, hit: bool, payload: JsonValue = field(opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

A run's result, as qvr run --json prints it.

PARAMETER DESCRIPTION
key

The digest of the run's key.

TYPE: str

hit

Whether the payload came from the store.

TYPE: bool

payload

The run's mutable JSON data, compared by identity.

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

FitCache

FitCache(store: ArtifactStore, *, engine: str | None = None, factories: Mapping[str, ArtifactFactory] | None = None)

A content-addressed cache of fits and runs in an artifact store.

PARAMETER DESCRIPTION
store

Where artifacts persist.

TYPE: ArtifactStore

engine

The engine identity digest; engine_identity when None. Results are reused only by the same engine.

TYPE: str or None DEFAULT: None

factories

Explicit contracts for configuration values the fitted artifact format does not know, passed to save_fit and load_fit.

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

Source code in src/quivers/incremental/fits.py
def __init__(
    self,
    store: ArtifactStore,
    *,
    engine: str | None = None,
    factories: Mapping[str, ArtifactFactory] | None = None,
) -> None:
    self.store = store
    self.engine = engine_identity() if engine is None else engine
    self.factories = dict(factories or {})
    self.log: list[FitCacheEvent] = []

for_project classmethod

for_project(start: Path | None = None) -> FitCache

The cache of the project a path belongs to.

PARAMETER DESCRIPTION
start

A path inside the project; the working directory when None.

TYPE: Path or None DEFAULT: None

RETURNS DESCRIPTION
FitCache

A cache in the project's artifact store.

RAISES DESCRIPTION
StoreError

If no project root is found.

Source code in src/quivers/incremental/fits.py
@classmethod
def for_project(cls, start: Path | None = None) -> FitCache:
    """The cache of the project a path belongs to.

    Parameters
    ----------
    start : Path or None
        A path inside the project; the working directory when None.

    Returns
    -------
    FitCache
        A cache in the project's artifact store.

    Raises
    ------
    StoreError
        If no project root is found.
    """
    return cls(ArtifactStore.for_project(start))

fit_key

fit_key(model: Model, data: Mapping[str, ExternalValue], *, method: InferenceMethod[ModelFit], parameters: Mapping[str, ExternalValue] | 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') -> FitKey

The key of a Model.fit call.

PARAMETER DESCRIPTION
model

The checked model.

TYPE: Model

data

The external data.

TYPE: Mapping[str, ExternalValue]

method

The inference method.

TYPE: InferenceMethod[ModelFit]

parameters

Static specialization arguments.

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

input

The domain input.

TYPE: Tensor or None DEFAULT: None

seed

The compilation seed.

TYPE: int DEFAULT: 0

sample_prior

The prior-sampling mode.

TYPE: PriorMode DEFAULT: 'no'

num_prior_samples

The prior draw budget.

TYPE: int DEFAULT: 100

prior_seed

The prior stream's seed.

TYPE: int DEFAULT: 1

snapshot_policy

The refit-data ownership.

TYPE: SnapshotPolicy DEFAULT: 'clone'

RETURNS DESCRIPTION
FitKey

The key.

RAISES DESCRIPTION
FitCacheError

If the model uses a custom family catalog, a datum or the method has no portable contract, the method declares no seed, or a datum names no parameter of the entry.

ValueError

If labeled data does not match the axes of its parameter's type.

Source code in src/quivers/incremental/fits.py
def fit_key(
    self,
    model: Model,
    data: Mapping[str, ExternalValue],
    *,
    method: InferenceMethod[ModelFit],
    parameters: Mapping[str, ExternalValue] | 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",
) -> FitKey:
    """The key of a `Model.fit` call.

    Parameters
    ----------
    model : Model
        The checked model.
    data : Mapping[str, ExternalValue]
        The external data.
    method : InferenceMethod[ModelFit]
        The inference method.
    parameters : Mapping[str, ExternalValue] or None
        Static specialization arguments.
    input : torch.Tensor or None
        The domain input.
    seed : int
        The compilation seed.
    sample_prior : PriorMode
        The prior-sampling mode.
    num_prior_samples : int
        The prior draw budget.
    prior_seed : int
        The prior stream's seed.
    snapshot_policy : SnapshotPolicy
        The refit-data ownership.

    Returns
    -------
    FitKey
        The key.

    Raises
    ------
    FitCacheError
        If the model uses a custom family catalog, a datum or the method
        has no portable contract, the method declares no seed, or a datum
        names no parameter of the entry.
    ValueError
        If labeled data does not match the axes of its parameter's type.
    """
    if model.families is not None and len(model.families.definitions) > 0:
        raise FitCacheError(
            "a model with native family implementations has no content "
            "identity: their Python code is not hashed"
        )
    content = ModuleContent(model.checked_module)
    entry = content.hashes.declaration("entry", model.entry)
    companions = content.value_hash(
        "companions",
        (
            model.schema.scoped_interpretations,
            model.schema.closed_interpretations,
            model.schema.packed_interpretations,
        ),
    )
    positions = {
        parameter.name: index
        for index, parameter in enumerate(model.schema.entry.parameters)
    }
    unknown = sorted(set(data) - set(positions))
    if unknown:
        raise FitCacheError(f"data name no parameter of the entry: {unknown}")
    # Labeled data keys the fit by its entries in canonical order.
    data = cast(Mapping[str, ExternalValue], model.aligned_data(data))
    codec = _Codec(self.factories)
    try:
        encoded_method = cast(JsonValue, codec.encode(method))
    except TypeError as error:
        raise FitCacheError(
            f"the inference method has no content identity: {error}"
        ) from error
    if _unseeded(encoded_method):
        raise FitCacheError(
            "the inference method declares no seed, so every run draws "
            "fresh randomness and no stored fit reproduces it"
        )
    configuration = tagged_digest(
        "fit-configuration",
        [
            _encoded_digest(codec, encoded_method),
            value_digest(dict(parameters or {}), self.factories),
            value_digest(input, self.factories),
            sample_prior,
            num_prior_samples,
            snapshot_policy,
        ],
    )
    return FitKey(
        kind="fit",
        entry=entry.hash,
        companions=companions,
        source=program_source_digest(model.source),
        names=entry.names,
        data=tuple(
            KeyedDigest(position=position, digest=digest)
            for position, digest in sorted(
                (positions[name], value_digest(value, self.factories))
                for name, value in data.items()
            )
        ),
        fixed_sites=(),
        configuration=configuration,
        seeds=(seed, prior_seed),
        engine=self.engine,
    )

fit

fit(model: Model, data: Mapping[str, ExternalValue], *, method: InferenceMethod[ModelFit], parameters: Mapping[str, ExternalValue] | 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') -> ModelFit

Fit a model, reusing a stored fit with the same key.

PARAMETER DESCRIPTION
model

The checked model.

TYPE: Model

data

The external data.

TYPE: Mapping[str, ExternalValue]

method

The inference method.

TYPE: InferenceMethod[ModelFit]

parameters

Static specialization arguments.

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

input

The domain input.

TYPE: Tensor or None DEFAULT: None

seed

The compilation seed.

TYPE: int DEFAULT: 0

sample_prior

The prior-sampling mode.

TYPE: PriorMode DEFAULT: 'no'

num_prior_samples

The prior draw budget.

TYPE: int DEFAULT: 100

prior_seed

The prior stream's seed.

TYPE: int DEFAULT: 1

snapshot_policy

The refit-data ownership.

TYPE: SnapshotPolicy DEFAULT: 'clone'

RETURNS DESCRIPTION
ModelFit

On a hit, the stored fit reloaded exactly as save_fit wrote it, bound to the source it was fitted from. On a miss, the new fit, after storing it.

RAISES DESCRIPTION
FitCacheError

If the fit has no content identity, or the method does not return a ModelFit.

StoreError

If the stored artifact is corrupt.

Source code in src/quivers/incremental/fits.py
def fit(
    self,
    model: Model,
    data: Mapping[str, ExternalValue],
    *,
    method: InferenceMethod[ModelFit],
    parameters: Mapping[str, ExternalValue] | 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",
) -> ModelFit:
    """Fit a model, reusing a stored fit with the same key.

    Parameters
    ----------
    model : Model
        The checked model.
    data : Mapping[str, ExternalValue]
        The external data.
    method : InferenceMethod[ModelFit]
        The inference method.
    parameters : Mapping[str, ExternalValue] or None
        Static specialization arguments.
    input : torch.Tensor or None
        The domain input.
    seed : int
        The compilation seed.
    sample_prior : PriorMode
        The prior-sampling mode.
    num_prior_samples : int
        The prior draw budget.
    prior_seed : int
        The prior stream's seed.
    snapshot_policy : SnapshotPolicy
        The refit-data ownership.

    Returns
    -------
    ModelFit
        On a hit, the stored fit reloaded exactly as `save_fit` wrote it,
        bound to the source it was fitted from. On a miss, the new fit,
        after storing it.

    Raises
    ------
    FitCacheError
        If the fit has no content identity, or the method does not return
        a `ModelFit`.
    StoreError
        If the stored artifact is corrupt.
    """
    key = self.fit_key(
        model,
        data,
        method=method,
        parameters=parameters,
        input=input,
        seed=seed,
        sample_prior=sample_prior,
        num_prior_samples=num_prior_samples,
        prior_seed=prior_seed,
        snapshot_policy=snapshot_policy,
    ).digest()
    stored = self.store.get("fit", key)
    if stored is not None:
        self.log.append(FitCacheEvent(kind="fit", key=key, hit=True))
        path = self.store.payload_path("fit", key)
        if path is None:
            raise FitCacheError(f"stored fit {key} disappeared while being read")
        loaded = load_fit(path, factories=self.factories)
        if not isinstance(loaded, ModelFit):
            raise FitCacheError(f"stored fit {key} is not a source fit")
        return loaded
    result = model.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,
    )
    if not isinstance(result, ModelFit):
        raise FitCacheError(
            "fit caching stores fitted artifacts; the method returned "
            f"{type(result).__name__}, not ModelFit"
        )
    staging = self.store.staging_path("fit")
    try:
        save_fit(result, staging, factories=self.factories)
        self.store.put("fit", key, staging.read_bytes(), label=f"fit {model.entry}")
    finally:
        staging.unlink(missing_ok=True)
    self.log.append(FitCacheEvent(kind="fit", key=key, hit=False))
    return result

run_key

run_key(module: QiecModule, name: str, arguments: Sequence[HostValue] = (), *, data: Mapping[str, HostValue] | None = None, sites: Mapping[str, HostValue] | None = None, static_arguments: Sequence[str] = (), runtime: RuntimeConfiguration | None = None, fuel: int | None = None, seed: int | None = None, numbers: NumberDomain | None = None) -> FitKey

The key of an invoke_entry run.

PARAMETER DESCRIPTION
module

The checked module.

TYPE: QiecModule

name

The entry's name: a program or a computation.

TYPE: str

arguments

Positional value arguments.

TYPE: Sequence[HostValue] DEFAULT: ()

data

A program's parameters by name.

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

sites

Conditioned sites by label.

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

static_arguments

NAME=TERM static arguments.

TYPE: Sequence[str] DEFAULT: ()

runtime

The runtime providers.

TYPE: RuntimeConfiguration or None DEFAULT: None

fuel

The step budget.

TYPE: int or None DEFAULT: None

seed

The reference generator's seed.

TYPE: int or None DEFAULT: None

numbers

The number domain the reference machine computes in; the default floating domain when None.

TYPE: NumberDomain or None DEFAULT: None

RETURNS DESCRIPTION
FitKey

The key.

RAISES DESCRIPTION
FitCacheError

If the run has no seed, uses programmatic providers, names a datum or site the entry does not have, or passes a value with no portable contract.

KeyError

If the module has no entry or computation of that name.

ExecutionFailure

With code qiec-run-data if labeled data does not match the axes of its parameter's type.

Source code in src/quivers/incremental/fits.py
def run_key(
    self,
    module: QiecModule,
    name: str,
    arguments: Sequence[HostValue] = (),
    *,
    data: Mapping[str, HostValue] | None = None,
    sites: Mapping[str, HostValue] | None = None,
    static_arguments: Sequence[str] = (),
    runtime: RuntimeConfiguration | None = None,
    fuel: int | None = None,
    seed: int | None = None,
    numbers: NumberDomain | None = None,
) -> FitKey:
    """The key of an `invoke_entry` run.

    Parameters
    ----------
    module : QiecModule
        The checked module.
    name : str
        The entry's name: a program or a computation.
    arguments : Sequence[HostValue]
        Positional value arguments.
    data : Mapping[str, HostValue] or None
        A program's parameters by name.
    sites : Mapping[str, HostValue] or None
        Conditioned sites by label.
    static_arguments : Sequence[str]
        ``NAME=TERM`` static arguments.
    runtime : RuntimeConfiguration or None
        The runtime providers.
    fuel : int or None
        The step budget.
    seed : int or None
        The reference generator's seed.
    numbers : NumberDomain or None
        The number domain the reference machine computes in; the
        default floating domain when None.

    Returns
    -------
    FitKey
        The key.

    Raises
    ------
    FitCacheError
        If the run has no seed, uses programmatic providers, names a datum
        or site the entry does not have, or passes a value with no
        portable contract.
    KeyError
        If the module has no entry or computation of that name.
    ExecutionFailure
        With code ``qiec-run-data`` if labeled data does not match the
        axes of its parameter's type.
    """
    if seed is None:
        raise FitCacheError(
            "a run without a seed continues the generator's state, so no "
            "stored run reproduces it; pass a seed to cache it"
        )
    configuration = runtime or RuntimeConfiguration()
    if configuration.providers:
        raise FitCacheError(
            "programmatic runtime providers have no content identity; "
            "select providers by name to cache a run"
        )
    content = ModuleContent(module)
    program = next((entry for entry in module.entries if entry.name == name), None)
    # Labeled data keys the run by its entries in the canonical order its
    # type fixes, so the order its rows were given in never changes the key.
    if program is None:
        arguments = aligned_arguments(module, name, arguments)
    elif data:
        data = aligned_data(module, name, data)
    declaration = content.hashes.declaration(
        "entry" if program is not None else "computation", name
    )
    positions: dict[str, int] = (
        {}
        if program is None
        else {
            parameter.name: index
            for index, parameter in enumerate(program.parameters)
        }
    )
    supplied: list[tuple[int, str]] = [
        (index, value_digest(value)) for index, value in enumerate(arguments)
    ]
    for datum, value in (data or {}).items():
        if datum not in positions:
            raise FitCacheError(f"{name!r} has no parameter {datum!r}")
        supplied.append((positions[datum], value_digest(value)))
    fixed: list[tuple[int, str]] = []
    for label, value in (sites or {}).items():
        if label not in declaration.names:
            raise FitCacheError(f"{name!r} has no site {label!r}")
        fixed.append((declaration.names.index(label), value_digest(value)))
    return FitKey(
        kind="run",
        entry=declaration.hash,
        companions="",
        source="",
        names=declaration.names,
        data=tuple(
            KeyedDigest(position=position, digest=digest)
            for position, digest in sorted(supplied)
        ),
        fixed_sites=tuple(
            KeyedDigest(position=position, digest=digest)
            for position, digest in sorted(fixed)
        ),
        configuration=tagged_digest(
            "run-configuration",
            cast(
                CoreJson,
                [
                    json.loads(json.dumps(configuration.to_data(), sort_keys=True)),
                    sorted(static_arguments),
                    fuel,
                    json.loads((numbers or NumberDomain()).model_dump_json()),
                ],
            ),
        ),
        seeds=(seed,),
        engine=self.engine,
    )

run

run(module: QiecModule, name: str, arguments: Sequence[HostValue] = (), *, data: Mapping[str, HostValue] | None = None, sites: Mapping[str, HostValue] | None = None, static_arguments: Sequence[str] = (), runtime: RuntimeConfiguration | None = None, fuel: int | None = None, seed: int | None = None, numbers: NumberDomain | None = None) -> CachedRun

Invoke an entry, reusing a stored run with the same key.

PARAMETER DESCRIPTION
module

The checked module.

TYPE: QiecModule

name

The entry's name.

TYPE: str

arguments

Positional value arguments.

TYPE: Sequence[HostValue] DEFAULT: ()

data

A program's parameters by name.

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

sites

Conditioned sites by label.

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

static_arguments

NAME=TERM static arguments.

TYPE: Sequence[str] DEFAULT: ()

runtime

The runtime providers.

TYPE: RuntimeConfiguration or None DEFAULT: None

fuel

The step budget.

TYPE: int or None DEFAULT: None

seed

The reference generator's seed; required.

TYPE: int or None DEFAULT: None

numbers

The number domain the reference machine computes in; the default floating domain when None.

TYPE: NumberDomain or None DEFAULT: None

RETURNS DESCRIPTION
CachedRun

The run's JSON payload, from the store on a hit.

RAISES DESCRIPTION
FitCacheError

If the run has no content identity.

ExecutionFailure

If the run fails.

StoreError

If the stored payload is corrupt.

Source code in src/quivers/incremental/fits.py
def run(
    self,
    module: QiecModule,
    name: str,
    arguments: Sequence[HostValue] = (),
    *,
    data: Mapping[str, HostValue] | None = None,
    sites: Mapping[str, HostValue] | None = None,
    static_arguments: Sequence[str] = (),
    runtime: RuntimeConfiguration | None = None,
    fuel: int | None = None,
    seed: int | None = None,
    numbers: NumberDomain | None = None,
) -> CachedRun:
    """Invoke an entry, reusing a stored run with the same key.

    Parameters
    ----------
    module : QiecModule
        The checked module.
    name : str
        The entry's name.
    arguments : Sequence[HostValue]
        Positional value arguments.
    data : Mapping[str, HostValue] or None
        A program's parameters by name.
    sites : Mapping[str, HostValue] or None
        Conditioned sites by label.
    static_arguments : Sequence[str]
        ``NAME=TERM`` static arguments.
    runtime : RuntimeConfiguration or None
        The runtime providers.
    fuel : int or None
        The step budget.
    seed : int or None
        The reference generator's seed; required.
    numbers : NumberDomain or None
        The number domain the reference machine computes in; the
        default floating domain when None.

    Returns
    -------
    CachedRun
        The run's JSON payload, from the store on a hit.

    Raises
    ------
    FitCacheError
        If the run has no content identity.
    ExecutionFailure
        If the run fails.
    StoreError
        If the stored payload is corrupt.
    """
    key = self.run_key(
        module,
        name,
        arguments,
        data=data,
        sites=sites,
        static_arguments=static_arguments,
        runtime=runtime,
        fuel=fuel,
        seed=seed,
        numbers=numbers,
    ).digest()
    stored = self.store.get("run", key)
    if stored is not None:
        self.log.append(FitCacheEvent(kind="run", key=key, hit=True))
        return CachedRun(key=key, hit=True, payload=json.loads(stored))
    result = invoke_entry(
        module,
        name,
        arguments,
        data=data,
        sites=sites,
        static_arguments=static_arguments,
        runtime=runtime,
        fuel=fuel,
        seed=seed,
        numbers=numbers,
    )
    text = json.dumps(result.to_data(), sort_keys=True)
    self.store.put("run", key, text.encode(), label=f"run {name}")
    self.log.append(FitCacheEvent(kind="run", key=key, hit=False))
    return CachedRun(key=key, hit=False, payload=json.loads(text))

program_source_digest

program_source_digest(source: ProgramSource) -> str

The digest that identifies a model's program source.

PARAMETER DESCRIPTION
source

The root module and the modules it imports.

TYPE: ProgramSource

RETURNS DESCRIPTION
str

The digest of each module's path with the alpha-normalized statement digest of its text (statements_digest), and of the hole fillings: invariant under comments, formatting, and renaming within each module, and changed by any other edit to any module of the program.

Source code in src/quivers/incremental/fits.py
def program_source_digest(source: ProgramSource) -> str:
    """The digest that identifies a model's program source.

    Parameters
    ----------
    source : ProgramSource
        The root module and the modules it imports.

    Returns
    -------
    str
        The digest of each module's path with the alpha-normalized statement
        digest of its text ([`statements_digest`][quivers.incremental.identity.statements_digest]),
        and of the hole fillings: invariant under comments, formatting, and
        renaming within each module, and changed by any other edit to any
        module of the program.
    """
    return tagged_digest(
        "program-source",
        cast(
            CoreJson,
            {
                "root": [source.module_path, statements_digest(source.root)],
                "modules": [
                    [item.path, statements_digest(item.text)] for item in source.modules
                ],
                "links": [[item.hole, item.module] for item in source.links],
            },
        ),
    )

value_digest

value_digest(value: ExternalValue | InferenceMethod[ModelFit], factories: Mapping[str, ArtifactFactory] | None = None) -> str

The digest of one external value.

PARAMETER DESCRIPTION
value

A datum, a site value, a configuration record, or an inference method: anything the fitted artifact format has a portable contract for.

TYPE: ExternalValue or InferenceMethod[ModelFit]

factories

Explicit contracts for values the format does not know.

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

RETURNS DESCRIPTION
str

The digest of the value's portable encoding.

RAISES DESCRIPTION
FitCacheError

If the value has no portable contract, so no stored fit could have been computed from it.

Source code in src/quivers/incremental/fits.py
def value_digest(
    value: ExternalValue | InferenceMethod[ModelFit],
    factories: Mapping[str, ArtifactFactory] | None = None,
) -> str:
    """The digest of one external value.

    Parameters
    ----------
    value : ExternalValue or InferenceMethod[ModelFit]
        A datum, a site value, a configuration record, or an inference
        method: anything the fitted artifact format has a portable contract
        for.
    factories : Mapping[str, ArtifactFactory] or None
        Explicit contracts for values the format does not know.

    Returns
    -------
    str
        The digest of the value's portable encoding.

    Raises
    ------
    FitCacheError
        If the value has no portable contract, so no stored fit could have
        been computed from it.
    """
    codec = _Codec(factories)
    try:
        encoded = cast(JsonValue, codec.encode(value))
    except TypeError as error:
        raise FitCacheError(f"a value has no content identity: {error}") from error
    return _encoded_digest(codec, encoded)