Skip to content

Python API

Normal recording returns a directory under <repo>/cherries/runs/YYYY/mm/dd/<UUIDv7>/. The date is the original local date in the persisted run.yaml start-time; finishing after midnight or transferring across timezones keeps the same partition. See the storage design.

liblaf.cherries

Record Python experiments as ordinary local files and portable remote archives.

Classes:

  • BaseConfig –

    Parameters defined in the experiment script, serialized as ordinary JSON.

Functions:

  • end –

    Record end-time, then save files, metrics and Git state; finalize directory.

  • fig –

    Return absolute study/figs/path, create parents and register the figure.

  • get_step –

    Return the current step, initially zero.

  • input –

    Return absolute study/data/path and register its end-of-run input copy.

  • log_metric –

    Append and flush one metric using the current step and time by default.

  • log_metrics –

    Append in mapping order, sharing step/time, and flush once without fsync.

  • output –

    Return absolute study/data/path, create parents and register the output.

  • run –

    Execute main and return its saved directory, or None when DEBUG=1.

  • set_step –

    Set the current step; logging does not increment it.

  • start –

    Begin at step zero; DEBUG=1 skips recording and retains workspace paths.

  • tmp –

    Return absolute study/tmp/path, creating parents without recording it.

Attributes:

__commit_id__ module-attribute

__commit_id__: str | None = None

__version__ module-attribute

__version__: str = '6.0.1.dev3+ga102f47f3'

__version_tuple__ module-attribute

__version_tuple__: tuple[int | str, ...] = (
    6,
    0,
    1,
    "dev3",
    "ga102f47f3",
)

BaseConfig pydantic-model

Bases: BaseModel

Parameters defined in the experiment script, serialized as ordinary JSON.

Show JSON schema:
{
  "description": "Parameters defined in the experiment script, serialized as ordinary JSON.",
  "properties": {},
  "title": "BaseConfig",
  "type": "object"
}

end

end() -> None

Record end-time, then save files, metrics and Git state; finalize directory.

Source code in src/liblaf/cherries/_runtime.py
def end() -> None:
    """Record end-time, then save files, metrics and Git state; finalize directory."""
    global _debugging  # noqa: PLW0603
    if _debugging:
        _debugging = False
        return
    _finish(publish=True)

fig

fig(path: Pathish) -> Path

Return absolute study/figs/path, create parents and register the figure.

Source code in src/liblaf/cherries/_runtime.py
def fig(path: Pathish) -> Path:
    """Return absolute study/figs/path, create parents and register the figure."""
    return _path("figs", path)

get_step

get_step() -> int

Return the current step, initially zero.

Source code in src/liblaf/cherries/_runtime.py
def get_step() -> int:
    """Return the current step, initially zero."""
    return _debug_step if _debugging else _current().step

input

input(path: Pathish) -> Path

Return absolute study/data/path and register its end-of-run input copy.

Source code in src/liblaf/cherries/_runtime.py
def input(path: Pathish) -> Path:  # noqa: A001
    """Return absolute study/data/path and register its end-of-run input copy."""
    return _path("inputs", path)

log_metric

log_metric(
    key: str,
    value: float,
    *,
    step: int | None = None,
    timestamp_ms: int | None = None,
) -> None

Append and flush one metric using the current step and time by default.

Source code in src/liblaf/cherries/_runtime.py
def log_metric(
    key: str,
    value: float,
    *,
    step: int | None = None,
    timestamp_ms: int | None = None,
) -> None:
    """Append and flush one metric using the current step and time by default."""
    log_metrics({key: value}, step=step, timestamp_ms=timestamp_ms)

log_metrics

log_metrics(
    metrics: Mapping[str, int | float],
    *,
    step: int | None = None,
    timestamp_ms: int | None = None,
) -> None

Append in mapping order, sharing step/time, and flush once without fsync.

Source code in src/liblaf/cherries/_runtime.py
def log_metrics(
    metrics: Mapping[str, int | float],
    *,
    step: int | None = None,
    timestamp_ms: int | None = None,
) -> None:
    """Append in mapping order, sharing step/time, and flush once without fsync."""
    if _debugging or not metrics:
        return
    current = _current()
    if current.metrics is None:
        current.metrics = (current.directory / "metrics.jsonl").open(
            "a", encoding="utf-8"
        )
    stamp = time.time_ns() // 1_000_000 if timestamp_ms is None else timestamp_ms
    for key, raw in metrics.items():
        value = float(raw)
        encoded = (
            value
            if math.isfinite(value)
            else {math.inf: "Infinity", -math.inf: "-Infinity"}.get(value, "NaN")
        )
        row = {
            "key": key,
            "value": encoded,
            "step": current.step if step is None else step,
            "timestamp_ms": stamp,
        }
        current.metrics.write(json.dumps(row, allow_nan=False) + "\n")
    current.metrics.flush()

output

output(path: Pathish) -> Path

Return absolute study/data/path, create parents and register the output.

Source code in src/liblaf/cherries/_runtime.py
def output(path: Pathish) -> Path:
    """Return absolute study/data/path, create parents and register the output."""
    return _path("outputs", path)

run

run(
    main: Callable[..., None],
    *,
    project_id: str | None = None,
    name: str | None = None,
    description: str | None = None,
    tags: Sequence[str] = (),
    metadata: Mapping[str, Any] | None = None,
) -> Path | None

Execute main and return its saved directory, or None when DEBUG=1.

Source code in src/liblaf/cherries/_runtime.py
def run(
    main: Callable[..., None],
    *,
    project_id: str | None = None,
    name: str | None = None,
    description: str | None = None,
    tags: Sequence[str] = (),
    metadata: Mapping[str, Any] | None = None,
) -> Path | None:
    """Execute main and return its saved directory, or None when DEBUG=1."""
    start(
        project_id=project_id,
        name=name,
        description=description,
        tags=tags,
        metadata=metadata,
    )
    try:
        if parameters := inspect.signature(main).parameters:
            config = get_type_hints(main)[next(iter(parameters))]()
            if not _debugging:
                current = _current()
                current.metadata["params"] = config.model_dump(mode="json")
                write_yaml(current.directory / "run.yaml", current.metadata)
            main(config)
        else:
            main()
    except BaseException as error:
        if _debugging:
            end()
            raise
        traceback.print_exc()
        try:
            _finish(publish=False)
        except Exception as recording_error:  # noqa: BLE001 - preserve the experiment failure
            error.add_note(f"Cherries recording failed: {recording_error}")
        raise
    if _debugging:
        end()
        return None
    return _finish(publish=True)

set_step

set_step(step: int) -> None

Set the current step; logging does not increment it.

Source code in src/liblaf/cherries/_runtime.py
def set_step(step: int) -> None:
    """Set the current step; logging does not increment it."""
    global _debug_step  # noqa: PLW0603
    if _debugging:
        _debug_step = step
    else:
        _current().step = step

start

start(
    *,
    project_id: str | None = None,
    name: str | None = None,
    description: str | None = None,
    tags: Sequence[str] = (),
    params: Mapping[str, Any] | None = None,
    metadata: Mapping[str, Any] | None = None,
) -> None

Begin at step zero; DEBUG=1 skips recording and retains workspace paths.

Source code in src/liblaf/cherries/_runtime.py
def start(
    *,
    project_id: str | None = None,
    name: str | None = None,
    description: str | None = None,
    tags: Sequence[str] = (),
    params: Mapping[str, Any] | None = None,
    metadata: Mapping[str, Any] | None = None,
) -> None:
    """Begin at step zero; DEBUG=1 skips recording and retains workspace paths."""
    global _active, _debugging, _debug_step  # noqa: PLW0603
    if _active is not None:
        raise RuntimeError("A Cherries run is already active")
    _debugging = os.getenv("DEBUG") == "1"
    _debug_step = 0
    if _debugging:
        return
    start_time = now()
    entry = _script()
    repo = _git.root(entry.parent)
    _git.preflight(repo)
    run_id = uuid7()
    directory = (
        repo / "cherries" / "runs" / run_relative_path(run_id, start_time)
    ).with_name(f"{run_id}.tmp")
    directory.mkdir(parents=True)
    data = {
        "project-id": project_id or repo.name,
        "run-id": run_id,
        "run-name": name or entry.stem,
        "start-time": start_time,
        "end-time": None,
        "tags": list(tags),
        "params": dict(params or {}),
        "commit": None,
        "metadata": dict(metadata or {}),
        "artifacts": empty_artifacts(),
    }
    if description is not None:
        data["description"] = description
    write_yaml(directory / "run.yaml", data)
    _active = _Run(directory, repo, entry, data, _Capture(directory / "run.log"))
    print(f"Cherries started {run_id}", file=sys.stderr)

tmp

tmp(path: Pathish) -> Path

Return absolute study/tmp/path, creating parents without recording it.

Source code in src/liblaf/cherries/_runtime.py
def tmp(path: Pathish) -> Path:
    """Return absolute study/tmp/path, creating parents without recording it."""
    base = _script().parent.parent / "tmp"
    result = (base / path).resolve()
    if result.relative_to(base) == Path():
        raise ValueError(f"Path must be inside {base}: {path}")
    result.parent.mkdir(parents=True, exist_ok=True)
    return result