Skip to content

Use Optuna to propose parameter candidates

The optional optpilot.optuna_generator.propose adapter connects Optuna's TPE sampler to the existing native generator protocol. OptPilot owns the frozen inputs, execution, retries and result ledger. Each generator call creates a short-lived in-memory Optuna study from released feedback and returns one candidate. It does not create another database or execution service.

This integration is available in the development checkout. Install it with uv sync --extra optuna, then run checkout commands with uv run --extra optuna. The extra adds Optuna and its dependencies; a base Core installation does not import or require Optuna. The adapter uses Optuna's public create_trial, add_trials and ask, and TPESampler interfaces.

Write a generator wrapper

from optpilot.optuna_generator import propose as optuna_propose

def propose(context):
    return optuna_propose(
        context,
        metric="daily_cost",
        direction="minimize",
        observations_per_candidate=3,
        n_startup_trials=5,
    )

Reference this wrapper as an ordinary manifest Generator entrypoint. Its source is frozen with the Generator. The installed adapter and Optuna version belong to the execution environment; the generator's runtime receipt records available installed distribution versions. Keep the same dependency lock for a repeatable run. Frozen project source alone does not reproduce a different Optuna release.

The adapter supports exactly one native parameter Task, one objective metric, and flat int, float, categorical and bool decisions. Numeric definitions require finite inclusive min and max. Categorical values must contain distinct finite JSON scalars; booleans sample false or true. Defaults do not fix a parameter during sampling. Unsupported types and extra options fail with an error instead of being silently ignored. There is no logarithmic, stepped, conditional, constrained, multi-objective or pruning interface in this adapter.

Decide which observations may train the optimizer

The Task must explicitly release the selected metric through feedbackMetrics. The adapter reads only the supplied context. It does not open the project, ledger, grader files or baseline implementation, and it never imports private instance values or raw evidence. Released baseline parameter values and scores are legitimate training observations under the same rule as generated values.

Set observations_per_candidate to the reviewed instance count multiplied by the repetition count. A candidate enters Optuna only if it has exactly that many usable observations. Scores are averaged into one Optuna trial per candidateVersionId; separate frozen versions with equal parameter values are not merged. Values must conform to the declared search space, and scores must be finite numbers, including zero. A missing metric, incompatible parameters, nonfinite score, explicit failed state or incomplete group causes that candidate to be omitted. Unknown outcomes are never replaced with zero or a failure penalty. Core normally omits failed trials entirely; a candidate with no successful feedback is therefore invisible to the optimizer.

Duplicate trialId values are rejected. Complete groups must have matching instance-version counts. The current feedback protocol does not expose a repetition number, so the adapter relies on Core's unique trial IDs for repeated coordinates; it cannot independently validate a forged repetition coordinate. The declared observation count must be correct: it cannot infer cases for which every candidate failed or a withheld metric that never appeared. Inspect run coverage and failures before treating a search result as a comparison.

Reproduce proposals

The adapter hashes the Study seed and generatedCount into an unsigned 32-bit sampler seed. Parameter names, candidate groups and feedback rows are ordered deterministically. The same context, wrapper configuration and dependency versions produce the same proposal; a later ordinal receives a different seed even when the feedback list is empty. This is a sequence of reconstructed studies, not a replay of the random-number state of one long-lived Optuna process.

n_startup_trials counts complete candidate versions, not individual evaluation rows. The default is 10. After that point TPE uses the retained objective values. The adapter explicitly uses independent TPE (multivariate=False) and disables constant-liar handling because it returns only one proposal at a time, with no concurrent Optuna trials. A repeated parameter mapping is possible and consumes a proposal slot. The adapter does not promise identical proposals across Optuna, NumPy or Python releases.

Run the inventory demonstration

From the repository root:

uv sync --extra optuna
uv run --extra optuna optpilot validate catalog/optuna_inventory/optpilot.experiment.yaml
uv run --extra optuna python catalog/optuna_inventory/run.py --output /tmp/optpilot-inventory-demo

Use a new output directory; on Windows choose an appropriate local path. The example README describes the synthetic model. Training evaluates 16 generated candidates plus a fixed policy on three demand scenarios. Only training cost is released to the generator. The runner then compares the selected frozen version with the fixed baseline on separate demand draws, without running a generator on holdout.

Open training.html and holdout.html in the output directory. summary.json records both run IDs and the selected version ID. The ledger retains each generation's exact input feedback and candidate versions for inspection. Training selection is optimistically biased; three synthetic holdout draws do not establish statistical significance or business value. This is a runnable integration example, not evidence of superiority over other optimizers.

The maintained optional contract suite uses real Optuna sampling and actual frozen Core workers:

uv run --extra optuna python -m unittest discover -s tests/core -p 'test_optuna_generator.py' -v