Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add pre eval callback and stringify user info for logging #109

Merged
merged 3 commits into from
Jun 9, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 27 additions & 11 deletions blackboxopt/optimization_loops/sequential.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,11 @@ def run_optimization_loop(
optimizer: Union[SingleObjectiveOptimizer, MultiObjectiveOptimizer],
evaluation_function: Callable[[EvaluationSpecification], Evaluation],
timeout_s: float = float("inf"),
max_evaluations: int = None,
max_evaluations: Optional[int] = None,
catch_exceptions_from_evaluation_function: bool = False,
pre_evaluation_callback: Optional[Callable[[EvaluationSpecification], Any]] = None,
post_evaluation_callback: Optional[Callable[[Evaluation], Any]] = None,
logger: logging.Logger = None,
logger: Optional[logging.Logger] = None,
) -> List[Evaluation]:
"""Convenience wrapper for an optimization loop that sequentially fetches evaluation
specifications until a given timeout or maximum number of evaluations is reached.
Expand All @@ -53,9 +54,12 @@ def run_optimization_loop(
exception raised by the evaluation function or instead store their stack
trace in the evaluation's `stacktrace` attribute. Set to True if there are
spurious errors due to e.g. numerical instability that should not halt the
optimization loop.
optimization loop. For more details, see the wrapper that is used internally
`blackboxopt.optimization_loops.utils.evaluation_function_wrapper`
pre_evaluation_callback: Reference to a callable that is invoked before each
evaluation and takes a `blackboxopt.EvaluationSpecification` as an argument.
post_evaluation_callback: Reference to a callable that is invoked after each
evaluation and takes a `blackboxopt.Evaluation` as its argument.
evaluation and takes a `blackboxopt.Evaluation` as an argument.
logger: The logger to use for logging progress. Default: `blackboxopt.logger`

Returns:
Expand All @@ -82,10 +86,13 @@ def run_optimization_loop(

try:
evaluation_specification = optimizer.generate_evaluation_specification()

logger.info(
"The optimizer proposed a specification for evaluation:\n"
+ f"{json.dumps(evaluation_specification.to_dict(), indent=2)}"
"The optimizer proposed the following evaluation specification:\n%s",
json.dumps(evaluation_specification.to_dict(), indent=2),
)
if pre_evaluation_callback is not None:
pre_evaluation_callback(evaluation_specification)

evaluation = evaluation_function_wrapper(
evaluation_function=evaluation_function,
Expand All @@ -94,16 +101,25 @@ def run_optimization_loop(
objectives=objectives,
catch_exceptions_from_evaluation_function=catch_exceptions_from_evaluation_function,
)

logger.info(
"Reporting the result from the evaluation function to the optimizer:\n"
+ f"{json.dumps(evaluation.to_dict(), indent=2)}"
"Reporting the following evaluation result to the optimizer:\n%s",
json.dumps(
{
# Stringify the user_info because it is not guaranteed to be
# json serializable
k: str(v) if k == "user_info" else v
for k, v in evaluation.to_dict().items()
},
indent=2,
),
)
optimizer.report(evaluation)
evaluations.append(evaluation)

if post_evaluation_callback is not None:
post_evaluation_callback(evaluation)

optimizer.report(evaluation)
evaluations.append(evaluation)

except OptimizerNotReady:
logger.info("Optimizer is not ready yet, retrying in two seconds")
time.sleep(2)
Expand Down
16 changes: 16 additions & 0 deletions tests/optimization_loops/sequential_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,19 @@ def callback(e: Evaluation):

assert len(evaluations) == len(evaluations_from_callback)
assert evaluations == evaluations_from_callback


def test_pre_evaluation_callback():
eval_specs_from_callback = []

def callback(e: Evaluation):
eval_specs_from_callback.append(e)

evaluations = run_optimization_loop(
RandomSearch(testing.SPACE, [Objective("loss", False)], max_steps=10),
lambda e: e.create_evaluation(objectives={"loss": 0.0}),
pre_evaluation_callback=callback,
)

assert len(evaluations) == len(eval_specs_from_callback)
assert [e.get_specification() for e in evaluations] == eval_specs_from_callback