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:
objectOne unit of work a benchmark runs, identified by its params.
paramsmay hold JSON types (None,bool,int, finitefloat,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
idis the hex SHA-256 of the canonical JSON ofparams. It is computed once at construction, so bad params fail immediately.Notes
paramsmust not be mutated after construction, because the id is cached.The path uses the defining module:
pyhealth.models.RNNserializes aspyhealth.models.rnn.RNN. Moving a class to another file changes the id.1and1.0give different ids.The id is unique only within one benchmark. Storage keys on
(benchmark.name, evaluation.id).
- params#
The evaluation’s parameters.
- Type:
- Raises:
TypeError – If
paramsholds 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
paramsholds 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
- classmethod from_dict(data)[source]#
Builds an evaluation from
to_dictoutput.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 byto_dict().- Return type:
- 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:
objectThe 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_typeis safe to display.artifactpoints 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 underoutput_dir. Likemetadata["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:
- metadata#
Any other information about the run.
- Type:
- artifact#
Path to the reusable output, or
Noneif 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'
- artifact: pathlib.Path | None = None#
- class pyhealth.benchmarks.Benchmark[source]#
Bases:
ABCA benchmark defines and executes evaluations.
Subclasses implement
nameand_evaluate(). Callers useevaluate(), which validates the evaluations, runs them and validates the results.- The
_evaluatecontract: Any order, grouping, or internal parallelism is allowed.
It returns one
Resultper evaluation, and catches per-evaluation failures as failed Results.cache_dirmay be shared by concurrent jobs, so writes are atomic (temporary file, thenos.replace).output_dirholds 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}
- 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:
- validate_results(evaluations, results)[source]#
Checks that the results match the evaluations.
Subclasses extend this via
super().- Parameters:
evaluations (
Sequence[Evaluation]) – The evaluations that were run.results (
Mapping[Evaluation,Result]) – The results returned by_evaluate().
- Raises:
ValueError – Unless
resultshas exactly one entry per evaluation. Every missing or extra entry is listed, one per line.- Return type:
- 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:
- Returns:
One
Resultper evaluation.- Raises:
ValueError – If the evaluations or the results fail validation.
- The