# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Durable records for ordered, seeded checkpoint evaluations.
"""Inspect evaluator dispatches and export recorded measurements."""
import argparse
from hashlib import sha256
import json
import os
from pathlib import Path
from time import perf_counter
import numpy as np
from qdpy.algorithms.sampling import _rollout_seed
from qdpy.base import SequentialExecutor, _atomic_output_path, generic_as_completed
from qdpy.phenotype import Individual
from qdpy.results import _decode_float, _json_value, _numeric_row
__all__ = ["read_evaluation_journal", "export_evaluation_dataset"]
_KIND = "qdpy-evaluation-journal"
def _encode(value):
return (json.dumps(value, allow_nan=False, separators=(",", ":")) + "\n").encode("utf-8")
def _read(path):
"""Read complete events; a crash can leave the last line incomplete."""
with Path(path).open("rb") as file:
line = file.readline()
if not line.endswith(b"\n"):
raise ValueError("Incomplete evaluation journal header.")
header = json.loads(line)
if header.get("kind") != _KIND or header.get("version") != 1:
raise ValueError("Unsupported evaluation journal.")
entries = {}
complete_at = len(line)
for line in file:
if not line.endswith(b"\n"):
break
row = json.loads(line, object_hook=_decode_float)
slot = row["id"]
if row["event"] == "dispatch":
entry = entries.setdefault(slot, {"id": slot, "seed": row["seed"], "genome": row["genome"],
"dispatches": 0})
if ("status" in entry or entry["genome"] != row["genome"] or entry["seed"] != row["seed"]):
raise ValueError(f"Inconsistent dispatch for evaluation {slot}.")
entry["dispatches"] += 1
elif row["event"] == "result":
if slot not in entries or "status" in entries[slot] or row["status"] not in ("ok", "failed"):
raise ValueError(f"Unexpected response for evaluation {slot}.")
entries[slot].update({key: value for key, value in row.items() if key not in ("id", "event")})
else:
raise ValueError("Unknown evaluation journal event.")
complete_at += len(line)
return header, entries, complete_at
## @brief Inspect recorded results without loading the native checkpoint.
[docs]
def read_evaluation_journal(path):
"""Return ordered records and actual returned calls plus dispatch counts.
A dispatch without a recorded response is uncertain. A worker may
have run that call before the driver lost its response. Such calls
are counted as uncertain separately from confirmed success and
evaluator failure.
"""
header, entries, _ = _read(path)
return _report(header, entries)
def _report(header, entries):
rows = [entries[slot] for slot in sorted(entries)]
dispatched = sum(row["dispatches"] for row in rows)
returned = sum("status" in row for row in rows)
return {"evaluation_key": header["evaluation_key"], "records": rows, "dispatches": dispatched,
"returned_calls": returned, "failed_calls": sum(row.get("status") == "failed" for row in rows),
"uncertain_calls": dispatched - returned}
def _prefix_digest(path, size):
checksum = sha256()
with path.open("rb") as file:
while size:
block = file.read(min(size, 1024 * 1024))
if not block:
raise ValueError("The journal was truncated during export.")
checksum.update(block)
size -= len(block)
return checksum.hexdigest()
## @brief Export aligned numeric arrays with evaluator and journal provenance.
# @param journal_path Source JSON Lines evaluation journal.
# @param output_path Destination for the pickle-free NPZ dataset.
# @return Metadata also stored in the dataset, including outcome counts and source digest.
[docs]
def export_evaluation_dataset(journal_path, output_path):
"""Write a pickle-free NPZ dataset of successful responses in slot order.
Archives contain two-dimensional float arrays named ``genomes``,
``fitness``, and ``descriptors``, with aligned unsigned 64-bit
``evaluation_ids`` and ``seeds``. Repeated genomes get separate
rows. Optional named scores use one JSON string per row. The JSON
``metadata`` includes the evaluator key, run ID, coordinator seed,
digest of the complete journal prefix, and omitted-call counts.
Export after the writer exits to capture the final run dataset.
"""
source, output = Path(journal_path), Path(output_path)
if source.resolve() == output.resolve():
raise ValueError("Use different paths for the journal and dataset.")
header, entries, end = _read(source)
counts = _report(header, entries)
rows = [row for row in counts.pop("records") if row.get("status") == "ok"]
def matrix(values):
if not rows:
return np.empty((0, 0), dtype=float)
try:
data = np.asarray([_numeric_row(row) for row in values], dtype=float)
except (TypeError, ValueError, OverflowError) as error:
raise ValueError("Dataset rows must have consistent, finite numeric values.") from error
if data.ndim != 2 or not np.isfinite(data).all():
raise ValueError("Dataset rows must have consistent, finite numeric values.")
return data
metadata = {"schema_version": 1, "journal_run": header["run"], "coordinator_seed": header["seed"],
"journal_sha256": _prefix_digest(source, end), "rows": len(rows), **counts}
arrays = {
"genomes": matrix(row["genome"] for row in rows),
"fitness": matrix(row["result"][0] for row in rows),
"descriptors": matrix(row["result"][1] for row in rows),
"evaluation_ids": np.asarray([row["id"] for row in rows], dtype=np.uint64),
"seeds": np.asarray([row["seed"] for row in rows], dtype=np.uint64),
"named_scores": np.asarray([json.dumps(_json_value(row["result"][2]), sort_keys=True)
if len(row["result"]) == 3 else "{}" for row in rows], dtype=str),
"metadata": json.dumps(metadata, sort_keys=True),
}
output.parent.mkdir(parents=True, exist_ok=True)
with _atomic_output_path(output) as temporary, temporary.open("wb") as file:
np.savez_compressed(file, **arrays)
return metadata
def main(argv=None):
"""Export a numeric dataset from one journal."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("journal")
parser.add_argument("output")
args = parser.parse_args(argv)
print(json.dumps(export_evaluation_dataset(args.journal, args.output), indent=2))
def _measure(evaluate, genome, seed):
"""Return a numeric response from a worker or a recorded evaluator failure."""
start = perf_counter()
try:
result = evaluate(Individual(genome), seed)
if not isinstance(result, (tuple, list)) or len(result) not in (2, 3):
raise ValueError("Return (fitness, descriptors) with an optional named score mapping.")
result = [_numeric_row(row) for row in result[:2]] + (
[_json_value(dict(result[2]))] if len(result) == 3 else []
)
except Exception as error:
return {"status": "failed", "error": f"{type(error).__name__}: {error}",
"seconds": perf_counter() - start, "result": None}
return {"status": "ok", "seconds": perf_counter() - start, "result": result}
class _JournalInterrupted(BaseException):
"""Carry an infrastructure failure through the native evaluator wrapper."""
class _EvaluationJournal:
def __init__(self, path, header, *, resume):
self.path = Path(path)
self.header = header
if resume:
saved, self.entries, end = _read(self.path)
if saved != header:
raise ValueError("The evaluation journal does not belong to this checkpoint.")
if end != self.path.stat().st_size:
with self.path.open("r+b") as file:
file.truncate(end)
os.fsync(file.fileno())
else:
self.entries = {}
self.path.parent.mkdir(parents=True, exist_ok=True)
self._write(header, "xb")
def _write(self, value, mode="ab"):
with self.path.open(mode) as file:
file.write(_encode(value))
file.flush()
os.fsync(file.fileno())
def _result(self, slot, response):
self._write({"event": "result", "id": slot, **response})
# Normalize tagged values exactly as the recovery path does.
if response["status"] == "ok" and len(response["result"]) == 3:
response["result"][2] = json.loads(_encode(response["result"][2]), object_hook=_decode_float)
self.entries[slot].update(response)
def evaluate(self, evaluate, batch, first_slot, executor):
"""Run missing slots and persist each response before native feedback."""
futures = {}
local = executor is None
executor = SequentialExecutor() if local else executor
try:
for slot, individual in enumerate(batch, first_slot):
genome = _numeric_row(individual)
seed = _rollout_seed(self.header["seed"], 0, slot)
entry = self.entries.get(slot)
if entry is not None:
if entry["genome"] != genome or entry["seed"] != seed:
raise ValueError(f"Restored proposal {slot} differs from the journal.")
if "status" in entry:
continue
self._write({"event": "dispatch", "id": slot, "seed": seed, "genome": genome})
if entry is None:
entry = self.entries[slot] = {"seed": seed, "genome": genome, "dispatches": 0}
entry["dispatches"] += 1
future = executor.submit(_measure, evaluate, genome, seed)
if local:
self._result(slot, future.result())
else:
futures[future] = slot
failure = None
while futures:
future = generic_as_completed(list(futures))
slot = futures.pop(future)
try:
response = future.result()
except Exception as error:
if failure is None:
failure = error
else:
self._result(slot, response)
if failure is not None:
raise failure
return [self.entries[slot]["result"] for slot in range(first_slot, first_slot + len(batch))]
except Exception as error:
raise _JournalInterrupted() from error
finally:
for future in futures:
future.cancel()
if __name__ == "__main__":
main()