Benchmarks#

pyhealth.benchmarks provides the base abstractions for benchmarks. A benchmark defines and executes evaluations. It knows nothing about runners, storage or leaderboards.

An Evaluation is one unit of work, identified by a hash of its parameters. A Benchmark runs a batch of evaluations and returns one Result per evaluation.

class pyhealth.benchmarks.Evaluation(params)[source]#

Bases: object

One unit of work a benchmark runs, identified by its params.

params may hold JSON types (None, bool, int, finite float, str, lists/tuples and str-keyed mappings) plus module-level classes and functions. Classes and functions are serialized by import path as {"__type__": "<module>.<qualname>"}, and that path must import back to the same object. Classes defined in __main__ (a script run directly or a notebook) are rejected: move them into an importable module.

The id is the hex SHA-256 of the canonical JSON of params. It is computed once at construction, so bad params fail immediately.

Notes

  • params must not be mutated after construction, because the id is cached.

  • The path uses the defining module: pyhealth.models.RNN serializes as pyhealth.models.rnn.RNN. Moving a class to another file changes the id.

  • 1 and 1.0 give different ids.

  • The id is unique only within one benchmark. Storage keys on (benchmark.name, evaluation.id).

params#

The evaluation’s parameters.

Type:

collections.abc.Mapping[str, Any]

id#

Hex SHA-256 of the canonical JSON of params.

Type:

str

Raises:
  • TypeError – If params holds a value that is not allowed, such as an arbitrary object, a lambda, a locally defined class, a class defined in __main__ or a class whose path doesn’t import back to it, or a mapping key that is not a string.

  • ValueError – If params holds NaN or infinity, or uses "__type__" as a key anywhere.

Examples

>>> from collections import OrderedDict
>>> ev = Evaluation({"model": OrderedDict, "lr": 0.001})
>>> ev.to_dict()
{'lr': 0.001, 'model': {'__type__': 'collections.OrderedDict'}}
>>> ev == Evaluation({"lr": 0.001, "model": OrderedDict})
True
>>> Evaluation.from_dict(ev.to_dict()) == ev
True
params: Mapping[str, Any]#
id: str#
to_dict()[source]#

Returns params as JSON-compatible data.

Return type:

dict[str, Any]

Returns:

The params, with classes and functions replaced by their {"__type__": ...} form.

classmethod from_dict(data)[source]#

Builds an evaluation from to_dict output.

This is the inverse of to_dict(): Evaluation.from_dict(ev.to_dict()) == ev. Each {"__type__": "<dotted.path>"} mapping is resolved to the class or function at that path. Public re-export paths are accepted, but the id always uses the defining-module path.

Parameters:

data (Mapping[str, Any]) – JSON-compatible params, as returned by to_dict().

Return type:

Evaluation

Returns:

The rebuilt evaluation.

Raises:

ValueError – If a path can’t be resolved, names something that is not a class or function, or shares its mapping with other keys.

Examples

>>> ev = Evaluation.from_dict({"c": {"__type__": "json.JSONDecoder"}})
>>> ev.to_dict()
{'c': {'__type__': 'json.decoder.JSONDecoder'}}
>>> Evaluation.from_dict(ev.to_dict()) == ev
True
class pyhealth.benchmarks.Result(status, metrics, metadata=<factory>, artifact=None)[source]#

Bases: object

The outcome of one evaluation.

By convention, a failed evaluation is returned as Result("failed", {}, {"error": str(exc), "error_type": type(exc).__name__}), so one failure doesn’t discard the batch.

metadata["error"] may contain patient data and must never be published. error_type is safe to display.

artifact points to the evaluation’s reusable output, such as a trained model checkpoint, so other benchmarks can load it instead of retraining. It may be a file or a directory, and is typically written under output_dir. Like metadata["error"], it may contain patient data (models can memorize training records) and must never be published.

status#

"success" or "failed".

Type:

Literal[‘success’, ‘failed’]

metrics#

Metric names mapped to values.

Type:

collections.abc.Mapping[str, Any]

metadata#

Any other information about the run.

Type:

collections.abc.Mapping[str, Any]

artifact#

Path to the reusable output, or None if the evaluation produced none.

Type:

pathlib.Path | None

Examples

>>> Result("success", {"accuracy": 0.9}).metrics
{'accuracy': 0.9}
>>> from pathlib import Path
>>> Result("success", {}, artifact=Path("runs/1/model.pt")).artifact.name
'model.pt'
>>> exc = ValueError("bad input")
>>> Result(
...     "failed", {}, {"error": str(exc), "error_type": type(exc).__name__}
... ).status
'failed'
status: Literal['success', 'failed']#
metrics: Mapping[str, Any]#
metadata: Mapping[str, Any]#
artifact: pathlib.Path | None = None#
class pyhealth.benchmarks.Benchmark[source]#

Bases: ABC

A benchmark defines and executes evaluations.

Subclasses implement name and _evaluate(). Callers use evaluate(), which validates the evaluations, runs them and validates the results.

The _evaluate contract:
  • Any order, grouping, or internal parallelism is allowed.

  • It returns one Result per evaluation, and catches per-evaluation failures as failed Results.

  • cache_dir may be shared by concurrent jobs, so writes are atomic (temporary file, then os.replace).

  • output_dir holds per-run artifacts. Results are always returned, never only written to disk.

Examples

>>> class Squares(Benchmark):
...     @property
...     def name(self):
...         return "squares"
...
...     def _evaluate(self, evaluations, cache_dir, output_dir):
...         return {
...             ev: Result("success", {"square": ev.params["x"] ** 2})
...             for ev in evaluations
...         }
>>> ev = Evaluation({"x": 3})
>>> Squares().evaluate([ev])[ev].metrics
{'square': 9}
abstract property name: str#

Lowercase identifier for the benchmark, e.g. "cpbench".

Return type:

str

validate_evaluations(evaluations)[source]#

Checks the evaluations before they run.

Subclasses extend this via super().

Parameters:

evaluations (Sequence[Evaluation]) – The evaluations to run.

Raises:

ValueError – If two evaluations share an id. Every duplicate is listed, one per line.

Return type:

None

validate_results(evaluations, results)[source]#

Checks that the results match the evaluations.

Subclasses extend this via super().

Parameters:
Raises:

ValueError – Unless results has exactly one entry per evaluation. Every missing or extra entry is listed, one per line.

Return type:

None

final evaluate(evaluations, cache_dir=None, output_dir=None)[source]#

Validates, runs and returns the results of the evaluations.

Exceptions escaping _evaluate() propagate unchanged.

Parameters:
  • evaluations (Sequence[Evaluation]) – The evaluations to run.

  • cache_dir (Optional[Path]) – Directory for reusable intermediate data, possibly shared by concurrent jobs.

  • output_dir (Optional[Path]) – Directory for per-run artifacts.

Return type:

dict[Evaluation, Result]

Returns:

One Result per evaluation.

Raises:

ValueError – If the evaluations or the results fail validation.

abstract _evaluate(evaluations, cache_dir, output_dir)[source]#

Runs the evaluations. See the class docstring for the contract.

Return type:

dict[Evaluation, Result]