Skip to content

Plans and hashes

plan

Resolving an experiment declaration into a closed, hashable plan.

An experiment names its entry, data, fixed values, inference method, seed, sweeps, the holes it fills, and the handlers it installs. Planning resolves all of these against the checked module graph and computes the experiment's identity without running anything:

  • the graph is loaded with the experiment's link clauses filling its holes, so the linked program is the one that runs;
  • a computation entry with handle clauses runs under those handlers: the plan adds the computation that installs them around the entry, outermost first, and runs that;
  • every data, fix, and sweep name must be a parameter of the entry (or, for a program run, a sample site);
  • each point of the sweeps' product is one run, and its point hash is the digest of the entry's content hash, the pinned data digests, the values given by name, the method and every option after defaults, and the seed. Names of the experiment, the entry, and the declarations do not enter it, so renaming any of them keeps the hash; any change to what the run computes changes it.

The experiment's hash is the digest of its points' hashes in sweep order.

EXPERIMENT_FORMAT module-attribute

EXPERIMENT_FORMAT = 'qvr-experiment/v1'

The format of an experiment's hash inputs; part of every hash.

WRAPPER_MEMBER module-attribute

WRAPPER_MEMBER = 'entry'

The member name of the computation that installs an experiment's handlers: experiment E runs E.entry.

PlannedData didactic-model

PlannedData(*, name: str, path: str, written: str, pin: ContentPin | None, line: int, column: int)

Bases: Model

A data clause with its file resolved.

PARAMETER DESCRIPTION
name

The parameter or site it gives a value to.

TYPE: str

path

The file, absolute.

TYPE: str

written

The path as the experiment writes it.

TYPE: str

pin

The pinned content hash.

TYPE: ContentPin | None

line

The clause's line.

TYPE: int

column

The clause's column.

TYPE: int

PointValue didactic-model

PointValue(*, name: str, value: str)

Bases: Model

One value given by name at a point.

PARAMETER DESCRIPTION
name

The parameter or site.

TYPE: str

value

The value as canonical JSON text.

TYPE: str

ExperimentPoint didactic-model

ExperimentPoint(*, index: tuple[int, ...], sweep: tuple[PointValue, ...], hash: str)

Bases: Model

One run of an experiment: one point of its sweeps' product.

PARAMETER DESCRIPTION
index

The position of each sweep's value, in sweep order; empty for an experiment without sweeps.

TYPE: tuple[int, ...]

sweep

The swept values at this point.

TYPE: tuple[PointValue, ...]

hash

The point hash.

TYPE: str

label property

label: str

The point as name=value pairs.

RETURNS DESCRIPTION
str

The swept values, or empty for the single point of an experiment without sweeps.

SourceFile didactic-model

SourceFile(*, path: str, module: str, digest: str, swhid: str)

Bases: Model

A source file of the program an experiment runs.

PARAMETER DESCRIPTION
path

The file.

TYPE: str

module

The module it is.

TYPE: str

digest

The BLAKE3 digest of its bytes.

TYPE: str

swhid

Its Software Heritage content identifier, swh:1:cnt:<sha1_git>, which names the file in the Software Heritage archive once it is archived.

TYPE: str

ExperimentPlan didactic-model

ExperimentPlan(*, name: str, file: str, line: int, root: str, entry: str, program: str, entry_kind: Literal['program', 'computation'], entry_hash: str, method: str, kind: MethodKind, options: tuple[PointValue, ...], seed: int, data: tuple[PlannedData, ...], fixed: tuple[PointValue, ...], points: tuple[ExperimentPoint, ...], hash: str, sources: tuple[SourceFile, ...], links: tuple[ExperimentLink, ...], handlers: tuple[str, ...], module: QiecModule = field(opaque=True, extras=OPAQUE_BY_VALUE), model: Model | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

An experiment resolved against its program, ready to run or hash.

PARAMETER DESCRIPTION
name

The experiment's name.

TYPE: str

file

The file declaring it.

TYPE: str

line

Its line.

TYPE: int

root

The module declaring it.

TYPE: str

entry

The entry it runs, a flat-program name (the handler-installing computation when the experiment installs handlers).

TYPE: str

program

The entry its program clause names, a flat-program name.

TYPE: str

entry_kind

Whether the entry is a program or a computation.

TYPE: Literal['program', 'computation']

entry_hash

The content hash of the entry; for a fit, combined with the interpretation bindings and the source's statement digest.

TYPE: str

method

The inference method.

TYPE: str

kind

Whether the method runs the entry or fits it.

TYPE: MethodKind

options

Every option of the method after defaults, sorted by name.

TYPE: tuple[PointValue, ...]

seed

The seed.

TYPE: int

data

The data clauses.

TYPE: tuple[PlannedData, ...]

fixed

The fixed values.

TYPE: tuple[PointValue, ...]

points

The runs, in sweep order.

TYPE: tuple[ExperimentPoint, ...]

hash

The experiment's hash.

TYPE: str

sources

The source files of the program.

TYPE: tuple[SourceFile, ...]

links

The holes filled.

TYPE: tuple[ExperimentLink, ...]

handlers

The handlers installed, as instance with handler, outermost first.

TYPE: tuple[str, ...]

module

The checked module the entry runs in.

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

model

For a fit, the live model of the program, compared by identity.

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

option_values

option_values() -> dict[str, OptionValue]

The method's options as values.

RETURNS DESCRIPTION
dict[str, OptionValue]

Each option's value, by name.

Source code in src/quivers/experiments/plan.py
def option_values(self) -> dict[str, OptionValue]:
    """The method's options as values.

    Returns
    -------
    dict[str, OptionValue]
        Each option's value, by name.
    """
    return {
        item.name: cast(OptionValue, json.loads(item.value))
        for item in self.options
    }

swhid

swhid(data: bytes) -> str

The Software Heritage identifier of a file's content.

PARAMETER DESCRIPTION
data

The file's bytes.

TYPE: bytes

RETURNS DESCRIPTION
str

swh:1:cnt: and the SHA-1 of the git blob of the bytes, the intrinsic identifier the archive gives the content.

Source code in src/quivers/experiments/plan.py
def swhid(data: bytes) -> str:
    """The Software Heritage identifier of a file's content.

    Parameters
    ----------
    data : bytes
        The file's bytes.

    Returns
    -------
    str
        ``swh:1:cnt:`` and the SHA-1 of the git blob of the bytes, the
        intrinsic identifier the archive gives the content.
    """
    header = f"blob {len(data)}\0".encode("ascii")
    return "swh:1:cnt:" + hashlib.sha1(header + data, usedforsecurity=False).hexdigest()

declared_experiments

declared_experiments(path: str | Path) -> tuple[ExperimentDecl, ...]

The experiments a module file declares, read without resolving them.

PARAMETER DESCRIPTION
path

A .qvr or .qvr.md file.

TYPE: str | Path

RETURNS DESCRIPTION
tuple[ExperimentDecl, ...]

Its experiments, in source order.

RAISES DESCRIPTION
OSError

If the file cannot be read.

ParseError

If it does not parse.

Source code in src/quivers/experiments/plan.py
def declared_experiments(path: str | Path) -> tuple[ExperimentDecl, ...]:
    """The experiments a module file declares, read without resolving them.

    Parameters
    ----------
    path : str | Path
        A ``.qvr`` or ``.qvr.md`` file.

    Returns
    -------
    tuple[ExperimentDecl, ...]
        Its experiments, in source order.

    Raises
    ------
    OSError
        If the file cannot be read.
    ParseError
        If it does not parse.
    """
    return parse(read_module_text(path), str(path)).experiments

point_hash

point_hash(*, kind: MethodKind, entry_hash: str, data: tuple[PlannedData, ...], values: tuple[PointValue, ...], method: str, options: tuple[PointValue, ...], seed: int) -> str

The hash of one run of an experiment.

PARAMETER DESCRIPTION
kind

Whether the run runs or fits the entry.

TYPE: MethodKind

entry_hash

The entry's content hash.

TYPE: str

data

The data clauses, each with its pin.

TYPE: tuple[PlannedData, ...]

values

The fixed and swept values.

TYPE: tuple[PointValue, ...]

method

The inference method.

TYPE: str

options

Its options after defaults.

TYPE: tuple[PointValue, ...]

seed

The seed.

TYPE: int

RETURNS DESCRIPTION
str

The digest of the experiment format and every input, each list sorted by name, so the order clauses are written in does not change it.

RAISES DESCRIPTION
ExperimentError

With code experiment-data-pin if a data clause has no pin.

Source code in src/quivers/experiments/plan.py
def point_hash(
    *,
    kind: MethodKind,
    entry_hash: str,
    data: tuple[PlannedData, ...],
    values: tuple[PointValue, ...],
    method: str,
    options: tuple[PointValue, ...],
    seed: int,
) -> str:
    """The hash of one run of an experiment.

    Parameters
    ----------
    kind : MethodKind
        Whether the run runs or fits the entry.
    entry_hash : str
        The entry's content hash.
    data : tuple[PlannedData, ...]
        The data clauses, each with its pin.
    values : tuple[PointValue, ...]
        The fixed and swept values.
    method : str
        The inference method.
    options : tuple[PointValue, ...]
        Its options after defaults.
    seed : int
        The seed.

    Returns
    -------
    str
        The digest of the experiment format and every input, each list
        sorted by name, so the order clauses are written in does not
        change it.

    Raises
    ------
    ExperimentError
        With code ``experiment-data-pin`` if a data clause has no pin.
    """
    pins: list[list[str]] = []
    for item in data:
        if item.pin is None:
            raise ExperimentError(
                "experiment-data-pin",
                f"data {item.name} is not pinned",
                line=item.line,
                column=item.column,
            )
        pins.append([item.name, item.pin.algorithm, item.pin.digest])
    return tagged_digest(
        "experiment-point",
        cast(
            CoreJson,
            {
                "format": EXPERIMENT_FORMAT,
                "kind": kind,
                "entry": entry_hash,
                "data": sorted(pins),
                "values": sorted([item.name, item.value] for item in values),
                "method": method,
                "options": [[item.name, item.value] for item in options],
                "seed": seed,
            },
        ),
    )

experiment_hash

experiment_hash(points: tuple[ExperimentPoint, ...]) -> str

The hash of an experiment: its points' hashes in sweep order.

PARAMETER DESCRIPTION
points

The experiment's points.

TYPE: tuple[ExperimentPoint, ...]

RETURNS DESCRIPTION
str

The digest of the point hashes with their indices.

Source code in src/quivers/experiments/plan.py
def experiment_hash(points: tuple[ExperimentPoint, ...]) -> str:
    """The hash of an experiment: its points' hashes in sweep order.

    Parameters
    ----------
    points : tuple[ExperimentPoint, ...]
        The experiment's points.

    Returns
    -------
    str
        The digest of the point hashes with their indices.
    """
    return tagged_digest(
        "experiment",
        [[list(point.index), point.hash] for point in points],
    )

plan_experiment

plan_experiment(path: str | Path, name: str | None = None, *, roots: tuple[str | Path, ...] | None = None) -> ExperimentPlan

Resolve one experiment of a module file into a plan.

PARAMETER DESCRIPTION
path

The .qvr or .qvr.md file declaring the experiment.

TYPE: str | Path

name

The experiment; the only one the file declares when None.

TYPE: str | None DEFAULT: None

roots

The directories module paths are relative to. When None, a module of a package is read in its package's build (quivers.packages.workspace.load_package_file), and any other file's imports are found below its own directory.

TYPE: tuple[str | Path, ...] | None DEFAULT: None

RETURNS DESCRIPTION
ExperimentPlan

The plan, with every point's hash.

RAISES DESCRIPTION
ExperimentError

If the experiment does not exist, names no entry, gives a value to a name the entry does not have, leaves a computation's parameter without one, names an unknown method or option, leaves data unpinned, installs a handler that does not apply, or runs a program with typed holes or unfilled holes.

ModuleError

If the module graph does not load or resolve.

ManifestError

If the manifest of the file's package is malformed.

PackageError

If an import or link of a package module crosses a package boundary the rules forbid, or its lockfile does not match the packages.

ParseError

If a module does not parse.

CompileError

If the program does not compile.

Source code in src/quivers/experiments/plan.py
def plan_experiment(
    path: str | Path,
    name: str | None = None,
    *,
    roots: tuple[str | Path, ...] | None = None,
) -> ExperimentPlan:
    """Resolve one experiment of a module file into a plan.

    Parameters
    ----------
    path : str | Path
        The ``.qvr`` or ``.qvr.md`` file declaring the experiment.
    name : str | None
        The experiment; the only one the file declares when None.
    roots : tuple[str | Path, ...] | None
        The directories module paths are relative to. When None, a module
        of a package is read in its package's build
        (`quivers.packages.workspace.load_package_file`), and any other
        file's imports are found below its own directory.

    Returns
    -------
    ExperimentPlan
        The plan, with every point's hash.

    Raises
    ------
    ExperimentError
        If the experiment does not exist, names no entry, gives a value to
        a name the entry does not have, leaves a computation's parameter
        without one, names an unknown method or option, leaves data
        unpinned, installs a handler that does not apply, or runs a program
        with typed holes or unfilled holes.
    ModuleError
        If the module graph does not load or resolve.
    ManifestError
        If the manifest of the file's package is malformed.
    PackageError
        If an import or link of a package module crosses a package boundary
        the rules forbid, or its lockfile does not match the packages.
    ParseError
        If a module does not parse.
    CompileError
        If the program does not compile.
    """
    file = str(path)
    declared = _select(declared_experiments(path), name, file)
    links = {link.hole: link.module for link in declared.links}
    packaged = load_package_file(path, links=links) if roots is None else None
    graph = (
        packaged
        if packaged is not None
        else load_file_graph(path, roots=roots, links=links)
    )
    flat = interpret(graph)
    if flat.unfilled:
        raise ExperimentError(
            "experiment-link",
            "the program needs holes no link fills: "
            + ", ".join(".".join(hole.path) for hole in flat.unfilled)
            + "; fill each with a `link <hole> = <module>` clause",
            file=file,
            line=declared.line,
            column=declared.col,
        )
    experiment = _select(flat.module.experiments, declared.name, file)
    statements = flat.module.statements
    target = _named(statements, experiment.program)
    if target is None:
        raise ExperimentError(
            "experiment-entry",
            f"{experiment.program} names no program or computation",
            file=file,
            line=experiment.program_line,
        )
    entry_name = experiment.program
    if experiment.handlers:
        if not isinstance(target, QiecComputationDecl):
            raise ExperimentError(
                "experiment-handler",
                f"{experiment.program} is a program, whose run fixes its "
                "handlers; an experiment installs handlers around a define",
                file=file,
                line=experiment.handlers[0].line,
                column=experiment.handlers[0].col,
            )
        wrapper = _wrapper(experiment, target, statements, file)
        entry_name = wrapper.name
        flat = flat.with_(module=flat.module.with_(statements=(*statements, wrapper)))
    module_name = module_stem(path)
    check_module_language(flat, module_name=module_name, file_path=file)
    module = Compiler(flat.module, module_name=module_name, file_path=file).qiec_module
    if module is None:
        raise ExperimentError(
            "experiment-entry",
            f"{experiment.program} is not an entry of the checked module",
            file=file,
            line=experiment.program_line,
        )
    try:
        refuse_holes(module, action="an experiment run")
    except HoleError as error:
        raise ExperimentError(
            "qiec-hole",
            str(error),
            file=file,
            line=experiment.line,
            column=experiment.col,
        ) from error
    method = experiment_method(experiment.infer.method)
    if method is None:
        names = ", ".join(item.name for item in experiment_methods())
        raise ExperimentError(
            "experiment-method",
            f"no inference method {experiment.infer.method!r}; the methods are {names}",
            file=file,
            line=experiment.infer.line,
            column=experiment.infer.col,
        )
    options = _options(method, experiment, file)
    point: EntryPoint = entry_point(module, entry_name)
    model: Model | None = None
    if method.kind == "fit":
        if point.kind != "program":
            raise ExperimentError(
                "experiment-method",
                f"{method.name} fits a program's posterior, and "
                f"{experiment.program} is a computation; run it with sample",
                file=file,
                line=experiment.infer.line,
                column=experiment.infer.col,
            )
        model = Model(ProgramSource.of_graph(graph, links), entry=entry_name)
        accepted = {parameter.name for parameter in model.schema.entry.parameters}
        kind_label = "parameter of the program"
    else:
        accepted = {parameter.name for parameter in point.parameters} | set(point.sites)
        kind_label = (
            "parameter or sample site of the program"
            if point.kind == "program"
            else "parameter of the computation"
        )
    named: dict[str, tuple[int, int]] = {}
    for item_name, line, column in (
        *((item.name, item.line, item.col) for item in experiment.data),
        *((item.name, item.line, item.col) for item in experiment.fixed),
        *((item.name, item.line, item.col) for item in experiment.sweeps),
    ):
        if item_name not in accepted:
            raise ExperimentError(
                "experiment-name",
                f"{item_name} is not a {kind_label} {experiment.program}; it "
                f"takes {', '.join(sorted(accepted)) or 'nothing'}",
                file=file,
                line=line,
                column=column,
            )
        if item_name in named:
            raise ExperimentError(
                "experiment-name",
                f"{item_name} is given a value twice (first at line {named[item_name][0]})",
                file=file,
                line=line,
                column=column,
            )
        named[item_name] = (line, column)
    if point.kind == "computation":
        missing = [p.name for p in point.parameters if p.name not in named]
        if missing:
            raise ExperimentError(
                "experiment-name",
                f"{experiment.program} needs a value for "
                + ", ".join(missing)
                + "; give each with data, fix, or sweep",
                file=file,
                line=experiment.line,
                column=experiment.col,
            )
    base = Path(path).resolve().parent
    data = tuple(
        PlannedData(
            name=item.name,
            path=str((base / item.path).resolve()),
            written=item.path,
            pin=item.pin,
            line=item.line,
            column=item.col,
        )
        for item in experiment.data
    )
    _check_data_pins(data, file)
    if model is not None:
        content = ModuleContent(model.checked_module)
        entry_hash = tagged_digest(
            "experiment-fit-entry",
            [
                content.hashes.declaration("entry", entry_name).hash,
                content.value_hash(
                    "companions",
                    (
                        model.schema.scoped_interpretations,
                        model.schema.closed_interpretations,
                        model.schema.packed_interpretations,
                    ),
                ),
                program_source_digest(model.source),
            ],
        )
    else:
        entry_hash = (
            ModuleContent(module)
            .hashes.declaration(
                "entry" if point.kind == "program" else "computation", entry_name
            )
            .hash
        )
    fixed = tuple(
        PointValue(name=item.name, value=item.value) for item in experiment.fixed
    )
    points: list[ExperimentPoint] = []
    sweeps = experiment.sweeps
    for index in itertools.product(*(range(len(sweep.values)) for sweep in sweeps)):
        swept = tuple(
            PointValue(name=sweep.name, value=sweep.values[position])
            for sweep, position in zip(sweeps, index, strict=True)
        )
        points.append(
            ExperimentPoint(
                index=tuple(index),
                sweep=swept,
                hash=point_hash(
                    kind=method.kind,
                    entry_hash=entry_hash,
                    data=data,
                    values=(*fixed, *swept),
                    method=method.name,
                    options=options,
                    seed=experiment.seed,
                ),
            )
        )
    return ExperimentPlan(
        name=experiment.name,
        file=file,
        line=experiment.line,
        root=module_display(flat.root),
        entry=entry_name,
        program=experiment.program,
        entry_kind=point.kind,
        entry_hash=entry_hash,
        method=method.name,
        kind=method.kind,
        options=options,
        seed=experiment.seed,
        data=data,
        fixed=fixed,
        points=tuple(points),
        hash=experiment_hash(tuple(points)),
        sources=_sources(flat),
        links=experiment.links,
        handlers=tuple(
            f"{item.instance} with {item.handler.name}" for item in experiment.handlers
        ),
        module=module,
        model=model,
    )