Reference
Hyperparameter tuning¶
model.tune(data) is the common entry point for
rd.ESN and rd.Model. It compares autonomous forecasts, installs a refitted
winner, and returns the same outer PyTorch module. The standalone
resdag.hpo.tune_model(model, data, ...) accepts the same advanced options.
Install resdag[hpo] for Optuna and joblib. Add the dynamics extra to accept
TSDynamics trajectories on Python 3.12 or newer.
Common tuning API¶
tuning
¶
Common, transactional tuning of fitted PyTorch reservoir models.
Optuna owns sampling and trial bookkeeping; joblib owns parallel processes. The data adapter owns immutable chronological views. Candidates use the same fit/forecast workflow as the final model, including named ports and units.
ScoreContext
dataclass
¶
ScoreContext(
predictions: dict[str, Tensor],
truth: dict[str, Tensor],
scales: dict[str, Tensor],
seed: int,
origin: int,
)
Original-unit tensors and fixed training scales for a custom objective.
Return one finite scalar per seed/origin. The trial score is their median.
Set direction='minimize' when returning an error rather than a reward.
PrefixScoreContext
dataclass
¶
PrefixScoreContext(
predictions: dict[str, Tensor],
truth: dict[str, Tensor],
scales: dict[str, Tensor],
seed: int,
origin: int,
completed_steps: int,
horizon: int,
)
Bases: ScoreContext
Explicitly prefix-safe pruning objective with the complete target horizon.
Predictions and truth contain only the admitted prefix. This callback
controls pruning, while objective still scores the complete forecast.
Keep its direction and scale comparable across matching resource steps.
TuningReport
dataclass
¶
TuningReport(
study: Study,
best_params: dict[str, Any],
best_trial: int,
score: float,
nrmse: float,
seeds: tuple[int, ...],
refit_seed: int,
validation: dict[str, Any],
protocol_hash: str,
attempts: int,
elapsed_seconds: float,
refit_seconds: float,
runs: tuple[dict[str, Any], ...],
_template: Model | ESN,
_installed_hash: str,
resources: dict[str, Any] = dict(),
)
Winning configuration, full Optuna study and reproducible validation facts.
tune_model
¶
tune_model(
model: Model | ESN,
training: Any,
targets: Any = None,
*,
preset: Preset = "balanced",
search_space: SearchSpace | None = None,
factory: Factory | None = None,
validation: tuple[Any, Any] | None = None,
validation_fraction: float = 0.2,
horizon: int | None = None,
n_trials: int | None = None,
seeds: Sequence[int] | None = None,
seed: int = 0,
n_origins: int | None = None,
threshold: float = 0.2,
aggregation: Literal["weakest", "mean"] = "weakest",
objective: Callable[[ScoreContext], float] | None = None,
pruning_objective: Callable[[PrefixScoreContext], float] | None = None,
direction: Literal["maximize", "minimize"] = "maximize",
sampler: BaseSampler | None = None,
pruner: str | BasePruner | None = None,
checkpoint_interval: int = 64,
study: Study | None = None,
storage: str | None = None,
study_name: str | None = None,
warm_start: Study | None = None,
transfer_mode: Literal["reevaluate", "scores"] = "reevaluate",
screening: bool | Screening | None = False,
memory_budget: MemoryBudget | str | int | None = None,
memory_estimator: (
Callable[[dict[str, Any], MemoryContext], MemoryEstimate | int] | None
) = None,
n_jobs: int = 1,
timeout: float | None = None,
inner_max_num_threads: int = 1,
catch_exceptions: bool = True,
execution: Literal["auto", "fast", "history"] = "auto"
) -> Model | ESN
Compare autonomous forecasts and install a fully refitted winner.
factory(params, seed) builds custom candidate DAGs. Without a factory,
custom models keep their weights/wiring and tune alpha/washout; presets
rebuild automatically. New attempts, including failed configurations, count
toward n_trials. A timeout stops new windows; running fits and final
refitting finish normally. Tune before constructing a PyTorch optimizer.
Source code in src/resdag/hpo/tuning.py
965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 | |
Data and validation¶
| Argument | Default | Contract |
|---|---|---|
training |
required | Floating (time, features) or (batch, time, features) tensors, a named tensor mapping, a bare trajectory, or named trajectory inputs. |
targets |
None |
Explicit named output targets, or implicit future observations for one input/output of equal width. Tensor targets are already aligned to input origins; trajectory targets are sampled at each head's physical prediction lead. |
validation |
None |
(inputs, targets_or_None) for an explicit later segment. It is excluded from both candidate fitting and final refitting. |
validation_fraction |
0.2 |
Chronological held-out fraction when validation is automatic. |
horizon |
None |
Complete scored length per origin. Default: half the available validation span, at least one sample. It stays the same across presets and candidates. |
n_origins |
preset | Number of distinct, evenly spread supported forecast starts; reduced if fewer complete windows exist. |
Automatic validation fits candidates on the earlier observations, then refits the winning configuration on all supplied development observations. Keep a separate final test set. Explicit validation stays held out during refitting; supply its later observations as forecast history when continuing after it.
Every origin uses the candidate's fixed readout and preprocessing. A later origin can synchronize on earlier validation observations without fitting on them. Complete windows can overlap. No unsupported horizon is silently shortened.
For an observed Tensor fit window of length C and largest head lead L,
shared supervised origins stop before C - L. This prevents future labels
crossing the fit boundary. The complete observed inputs are still retained for
forecast history. The same physical-support rule applies during final refitting;
validation["refit_discarded_target_rows"] reports discarded rows by head.
Standalone fit(inputs, tensor_targets) trusts the caller's aligned rows;
tuning deliberately caps them to the observed development window.
With explicit origin-aligned Tensor validation, the first scored forecast starts
after max(prediction_leads) validation observations. For example, leads one
and three skip the first three validation observations before selecting scored
origins. first_validation_index includes the preceding training length.
Trajectory truth is queried at physical dates and uses its actual source support
instead. Inputs and validation targets must preserve component names/order.
Trajectory interpolation is prepared once per fixed view from raw source slices. Training and origin histories cannot use later source values in interpolation coefficients. A named clock can require unscored preroll to reach the requested validation date; reports preserve its actual endpoint, first scored date and skip count. Forecasts still receive only declared non-feedback future drivers.
Search and repetitions¶
| Argument | Default | Contract |
|---|---|---|
preset |
"balanced" |
quick: 8 trials/1 seed/1 origin; balanced: 24/3/3; thorough: 80/5/5. |
n_trials |
preset | Positive budget of new attempts in this call; failures, pruning, memory rejection and screening rejection count. Timeout can stop early. |
search_space |
built-in | search_space(optuna_trial) -> mapping; ordinary Optuna suggestions and conditional branches. Return fixed settings alongside sampled settings. |
factory |
built-in | factory(params, seed) -> Model or ESN, rebuilding custom candidates. Accepted on a Model; the ESN preset rebuilds itself. |
seed |
0 |
Sampler seed and start of the default initialization seed bank. |
seeds |
preset | Explicit nonempty seed sequence; duplicates are removed. The same bank evaluates every configuration. |
Built-in rd.ESN and unmodified classic/OTT graphs wrapped in rd.Model use
the following space. All presets use the same ranges; presets change the
number of trials, seeds and starting points.
| Setting | Default range | Sampling |
|---|---|---|
reservoir_size |
Half to twice the initial width, each bound at least eight | Integer |
spectral_radius |
0.05–1.5 | Uniform |
leak_rate |
0.05–1.0 | Uniform |
alpha |
1e-12–1e-2 |
Logarithmic, when the readout exposes this setting |
input_scaling |
1e-3–2.0 |
Logarithmic, when supported by the input initializer |
bias_scaling |
1e-3–1.0 |
Logarithmic, when bias uses its default initializer |
mean_degree |
Three to twelve, capped by available recurrent inputs | Integer, for the default or configured Erdős–Rényi topology |
input_to_readout |
True, False |
Categorical, vanilla recipes only; input plus states or states alone |
mean_degree is a tuning control for the automatic recipe. It controls the
expected number of recurrent matrix entries per
unit, including one for a permitted self-connection. It determines the
Erdős–Rényi probability for the candidate's sampled width; the actual sampled
connection count varies. Existing topology flags and initializer settings are
preserved. A custom non-Erdős–Rényi topology, disabled bias or custom bias
initializer keeps its own construction rather than being replaced merely to
expose another search dimension.
Named input initializers and InputFeedbackInitializer objects support the
shared scaling control without losing their other options. Arbitrary matrix
callables and FunctionInitializer objects keep their original construction;
the tuner cannot assume that they accept or honor a scaling keyword. Supply
an explicit factory when you want to search their own settings.
search_space replaces the default space completely. Return only the settings
you want to vary or fix, using ordinary Optuna suggestions for any ranges.
Current workflow settings and custom transforms are copied into candidates;
the winner is refitted rather than inheriting fitted transform statistics.
Without a factory, a custom Model keeps its DAG and reservoir weights. This
also applies when the structure or reservoir weights of a built-in graph have
been edited after construction: automatic rebuilding must not discard edits. The
default search varies alpha; supplied settings may contain only alpha and
washout. It evaluates one initialization seed, since copying frozen weights
does not create a different reservoir. Its readouts must support the chosen
setting. A factory enables structural changes and multiple initialization seeds.
Ordinary fitting, recurrent memory, device/dtype changes, copying and portable save/load retain an eligible built-in recipe. A portable graph whose initializer recipe contains unsupported local Python code still saves its materialized weights; its automatic rebuilding recipe is omitted. After loading, use a custom factory to tune its architecture, or a trusted bundle when you need to retain that local Python recipe. See save and load.
Recipes can vary hidden widths, layer families, initialization and preprocessing. They must retain declared input/output names and widths, prediction leads, feedback routes/delays, and resampling settings. Returned settings must be finite JSON-compatible Python data; tuples are retained during reconstruction. Capture modules, initializer objects and callables in the factory instead of returning them as trial parameters. Forward the supplied seed when constructing reservoirs.
Scoring¶
| Argument | Default | Contract |
|---|---|---|
threshold |
0.2 |
Positive threshold for the RMS of per-feature normalized errors. Accuracy requires error strictly below this value. |
aggregation |
"weakest" |
Minimum head horizon; "mean" averages head horizons. |
objective |
None |
objective(ScoreContext) -> finite scalar replaces the ranking. |
pruning_objective |
None |
Optional pruning_objective(PrefixScoreContext) -> finite scalar enables custom within-forecast pruning while preserving the complete final objective. |
direction |
"maximize" |
Built-in horizon uses maximize. Set "minimize" for a custom error objective. |
The default counts each batch item's contiguous accurate prefix, stopping at
the first threshold failure. Each head uses the batch median, averaging the
two middle values for an even batch. "weakest" selects the shortest head
horizon. Thus horizons of 400 and 100 yield 100. The trial score is the median
across its initialization-seed/origin evaluations. Scores are positive sample
counts; zero is possible. The winner is refitted with the first seed in the bank.
Scoring divides each feature's original-unit error by a fixed training-label population standard deviation. The scale uses the prototype's absolute washout, not a trial's tuned washout or any validation prefix. Constant features use scale one; nonconstant scales have a dtype-epsilon floor. Half-precision scale calculation uses float32. This scoring scale is separate from model preprocessing.
ScoreContext fields are named predictions, truth, scales, plus seed and
origin. Predictions/truth retain the data's 2-D/3-D layout and original units.
Truth and scale tensors are cloned for custom objectives. A callback receives
one full seed/origin forecast and returns one finite scalar; the tuner takes
its median across runs. Built-in diagnostics remain available with a custom
objective. Nonfinite forecasts, scales or objective values fail the evaluation.
PrefixScoreContext adds completed_steps and the complete requested horizon.
Its prediction/truth tensors contain only the completed prefix. A prefix callback
controls pruning, not final ranking, and must return comparable finite values
at matching resource steps with the study's direction. Without this explicit
callback, a custom complete objective is evaluated only on full forecasts;
pruning can then skip later origins/seeds but not shorten the current forecast.
nrmse is a diagnostic: each head's full-window RMS normalized error, averaged
across heads with feature-count weights, then aggregated by the median across
runs. It does not break ties in the default horizon objective. Trajectory
reports include dt; multiply a horizon by it for physical duration.
Execution and budgets¶
| Argument | Default | Contract |
|---|---|---|
n_jobs |
1 |
Caller process by default; other nonzero integers use joblib workers (-1 selects available CPUs). |
inner_max_num_threads |
1 |
Positive worker BLAS-thread limit. |
timeout |
None |
Stops dispatching new windows after elapsed seconds; preparation counts toward this time. Running windows and final refitting finish. |
catch_exceptions |
True |
Failed candidate evaluations become Optuna FAIL trials; False raises the original exception. Setup/search errors still raise. |
execution |
"auto" |
Select fast step execution when supported, history replay for temporal DAGs; "fast" and "history" force a mode. |
pruner |
None |
Registry key or configured Optuna pruner; the parent owns pruning decisions. A supplied study owns its pruner instead. |
checkpoint_interval |
64 |
Positive scored-sample chunk length. Rejection at a checkpoint prevents later forecast chunks/evaluations. |
screening |
False |
True uses Screening(); a policy customizes cheap repetition counts, promotion fraction and cohort size. Full evaluation remains the default. |
memory_budget |
None |
Integer bytes, a size string or MemoryBudget; estimated admission/concurrency policy, never a process/RSS/GPU allocator cap. |
memory_estimator |
None |
estimator(params, MemoryContext) -> MemoryEstimate or int; required with a custom factory and budget. Returns complete totals, floored by known resident requirements. |
The parent samples a finite candidate window before workers evaluate it. Failed candidates consume attempts, and no window dispatches beyond the remaining trial budget. A timeout is a dispatch boundary, not cancellation of an ongoing fit/forecast and not a hard total deadline. Preparation and bookkeeping also consume elapsed time. A run with no valid completed candidate raises.
Workers receive prepared numerical jobs, without a study or storage connection. The parent owns sampling, real Optuna trial reports and pruning. Joblib/loky owns process creation, cancellation and reuse; there is no fork-based worker launcher. Errors/interruptions cancel outstanding work and finalize this call's unfinished reservations without replacing the original model.
All candidates use the same fixed data/seed protocol, but an adaptive sampler can propose a different sequence at a different worker count. Caller Python, NumPy and Torch RNG states are restored around search/evaluation callbacks. Fit/forecast timings synchronize accelerators before recording elapsed time. Fit time is recorded once per seed, on its first origin; later origins record zero fit time. Outer module identity, mode and hooks survive successful tuning; parameters can be replaced. Create optimizers afterward. A failed final refit or owned-storage cleanup leaves the original model unchanged.
Built-in scoring accumulates fixed-scale statistics while forecasts stream.
Resource steps are completed_seed_origin_count * horizon + completed_prefix,
so intermediate values from matching resources are comparable across trials.
The reported intermediate value is the median of completed evaluations and the
current prefix score. No pruner is used during the optional screening stage.
The common pruner="threshold" preset uses ThresholdPruner(lower=0.1,
n_warmup_steps=2 * checkpoint_interval) for positive horizon scores. It rejects
that string preset with a custom objective; pass a configured Optuna instance
with appropriate bounds instead. Other shared keys are "none", "median",
"asha" and "hyperband". The sample-accuracy threshold=0.2 is a separate setting.
Screening uses the same complete horizon with fewer seeds/origins, then ranks
each cohort and fully evaluates the promoted configurations. With balanced
defaults, all 24 candidates use one seed/origin first; the best eight receive
all three seeds and three origins. Only full evaluations become eligible
COMPLETE winners. Nonpromoted, oversized and timeout-unsubmitted candidates
are recorded as PRUNED, with reasons. A later full evaluation can still be
pruned by Optuna. See tuning resources.
Memory admission accounts for complete winner refits, known long warmup traces, retained custom-objective predictions and history replay. A custom factory changing execution capabilities must estimate its own temporary/replay needs. Individually oversized candidates are skipped before construction; estimated concurrency is reduced for candidates that fit individually. The source model's architecture and precision are never silently changed to satisfy a budget.
Optuna studies and resumption¶
| Argument | Default | Contract |
|---|---|---|
study |
None |
Caller-owned single-objective Optuna study with a matching direction and protocol. Queued trials are supported. |
sampler |
seeded TPESampler |
Used when ResDAG creates the study. |
storage |
memory | Journal path, SQLite .db path or supported storage URL. |
study_name |
generated | Persistent study name; provide it with storage to resume a named study. |
warm_start |
None |
Source Optuna study whose complete configurations are queued for reevaluation by default. |
transfer_mode |
"reevaluate" |
"scores" explicitly imports evaluated values only for identical bound protocols and objective directions. |
Pass study= or storage/study-name/sampler/pruner settings. A supplied study owns
its sampler, pruner and connections. An unbound study may contain queued WAITING
configurations; unverified evaluated scores cannot enter the new protocol.
The protocol binds prepared data, splits/origins/scales, task timing, seed bank, model configuration, search/objective/recipe configuration and relevant library environment. Changed data, callables or model configuration require a fresh study. Keep callbacks deterministic from their arguments and captured settings. The common tuner checks protocol compatibility before appending attempts. Resuming the same fitted model reuses its original candidate template, rather than treating the fitted winner as a new starting experiment.
Settings transfer preserves fixed returned values, suggestions and source
study/trial provenance. Reevaluation queues single-objective results best-first
(trial number breaks ties). Queued configurations consume attempts when run;
those beyond this call's budget remain WAITING. Imported scores do not consume
new attempts, but only exact matching protocols/directions allow them to compete.
Owned RDB sessions/pools are released before installing the winner. Returned studies remain usable and reconnect when required; SQLite memory pools remain alive while needed to retain the study. Caller-owned studies retain ownership.
Report fields¶
| Field | Meaning |
|---|---|
study |
Full, usable Optuna study. |
best_params, best_trial |
Resolved winning settings, including fixed values, and trial number. |
score, nrmse |
Winning objective and full-window normalized-error diagnostic. |
seeds, refit_seed |
Evaluation bank and seed used for final refitting. |
validation |
Split/refit policy, supervised windows, discarded rows, horizon, clock and actual origins. |
protocol_hash |
Fingerprint checked when resuming. |
attempts |
New attempts made by this call. |
elapsed_seconds, refit_seconds |
Total elapsed time and final fitting time. |
runs |
Winning configuration's per-seed/origin scores, head metrics and timings. |
resources |
Requested/effective jobs, maximum running jobs, screening/promotion counts, memory skips, pruning and timeout outcome. |
Optuna trial attributes also retain resolved parameters, seeds, run diagnostics
and evaluation error messages. screening_runs/screening_score describe cheap
evaluations; partial pruned runs identify complete=False and completed steps.
memory_estimate records totals and any requested-versus-known-minimum floor.
Optuna's ordinary best_params contains sampled
parameters; use the report's best_params when fixed returned settings matter.
Advanced raw runner¶
run_hpo consumes manually prepared five-array data loaders and raw ESNModel
creators. It returns a study; callers reconstruct the winner themselves. See the
raw HPO guide for an end-to-end example.
| Contract | Common model.tune |
Raw run_hpo |
|---|---|---|
| Data | Chronological/named/trajectory preparation | Explicit five-array loader and driver companions |
| Result | Same module with a refitted winner | Optuna study |
| Parallel count | n_jobs, joblib conventions |
Positive n_workers |
| Default objective | Positive accurate horizon, maximized | Negated expected horizon, minimized |
| Checkpoint step | Cumulative scored samples across seed/origin cases | 1-based checkpoint index; actual prefix length is recorded |
| Prefix normalization | Fixed training scales | Existing raw loss normalization, potentially prefix-dependent |
| Threshold-pruner preset | lower=0.1, warmup 2 * checkpoint_interval |
upper=-0.1, two checkpoint-index warmup steps |
Both use parent-owned Optuna bookkeeping and managed joblib/loky numerical
workers. Search/data callbacks, sampler, pruner, user trial callbacks and storage
stay in the parent. In-memory studies work with multiple workers. Finite windows
respect the number of new attempts requested, including FAIL and PRUNED.
Queued transfer configurations count when evaluated; imported old scores do not.
hpo
¶
Hyperparameter Optimization¶
This module provides Optuna-based hyperparameter optimization for ESN models. It supports multiple loss functions specialized for time series forecasting and chaotic systems.
Installation
This module requires the optional optuna dependency:
pip install resdag[hpo]
or:
pip install optuna
| FUNCTION | DESCRIPTION |
|---|---|
run_hpo |
Run hyperparameter optimization study. |
get_loss |
Get a loss function by name. |
get_study_summary |
Generate summary of completed study. |
resolve_pruner |
Resolve a pruner key/instance to an |
Pruners
Pass pruner= to run_hpo to enable Optuna early stopping, fed by the
per-trial intermediate forecast-horizon reports. Registry keys (PRUNERS):
"asha": ASHA / SuccessiveHalvingPruner"hyperband": Hyperband pruner"median": Median pruner (recommended starting point)"threshold": Threshold pruner"none": NopPruner (no pruning, the default)
Loss Functions
The following loss functions are available:
"efh": Expected Forecast Horizon (default, recommended for chaotic systems)"forecast_horizon": Forecast Horizon Loss (contiguous valid steps)"lyapunov": Lyapunov-weighted Loss (exponential decay)"standard": Standard Loss (mean geometric mean error)"soft_horizon": Soft valid horizon (cumulative survival probability)
Examples:
Basic HPO workflow:
>>> from resdag.hpo import run_hpo, get_study_summary
>>> from resdag.models import ott_esn
>>>
>>> def model_creator(reservoir_size, spectral_radius):
... return ott_esn(
... reservoir_size=reservoir_size,
... feedback_size=3,
... output_size=3,
... spectral_radius=spectral_radius,
... )
>>>
>>> def search_space(trial):
... return {
... "reservoir_size": trial.suggest_int("reservoir_size", 100, 500, step=50),
... "spectral_radius": trial.suggest_float("spectral_radius", 0.5, 1.5),
... }
>>>
>>> def data_loader(trial):
... return {
... "warmup": warmup, "train": train, "target": target,
... "f_warmup": f_warmup, "val": val,
... }
>>>
>>> study = run_hpo(
... model_creator=model_creator,
... search_space=search_space,
... data_loader=data_loader,
... n_trials=50,
... )
>>> print(get_study_summary(study))
See Also
resdag.training.ESNTrainer : Training interface. resdag.utils.data : Data loading utilities.
run_hpo
¶
run_hpo(
model_creator: Callable[..., ESNModel],
search_space: Callable[[Trial], dict[str, Any]],
data_loader: Callable[[Trial], dict[str, Any]],
n_trials: int,
loss: str | LossProtocol = "efh",
loss_params: dict[str, Any] | None = None,
targets_key: str = "output",
drivers_keys: list[str] | None = None,
monitor_losses: list[str | LossProtocol] | None = None,
monitor_params: dict[str, dict[str, Any]] | None = None,
study_name: str | None = None,
storage: str | None = None,
warm_start: list[dict[str, Any]] | None = None,
transfer_from: Study | str | None = None,
sampler: BaseSampler | None = None,
pruner: str | BasePruner | None = None,
seed: int | None = None,
device: str | device | None = None,
n_workers: int = 1,
verbosity: int = 1,
catch_exceptions: bool = True,
penalty_value: float = 10000000000.0,
clip_value: float | None = None,
prune_on_clip: bool = False,
horizon_key: str | None = None,
n_checkpoints: int = 5,
torch_scoring: bool = True,
trial_callbacks: list[TrialCallback] | None = None,
error_policy: Literal["fail", "penalty"] = "fail",
*,
transfer_mode: Literal["reevaluate", "scores"] = "reevaluate",
task_context: Mapping[str, Any] | str | None = None,
inner_max_num_threads: int = 1,
memory_budget: MemoryBudget | int | str | None = None,
memory_estimator: (
Callable[[dict[str, Any], MemoryContext], MemoryEstimate | int] | None
) = None
) -> Study
Tune raw ESNModel factories with explicit five-array data preparation.
The usual Model.tune/ESN.tune workflow prepares chronological views
and installs its winner. This advanced entry point returns an Optuna study;
callers own split alignment, scaling and winner reconstruction.
n_trials counts NEW attempts in this call, including failures/pruning.
Single-worker jobs run in the caller; multiple workers use the shared
managed joblib/loky executor, including notebook closures. Search-space and
data callbacks run once per new attempt in the parent with a real Trial.
Numerical workers receive no study/storage connection. Trial callbacks and
all Optuna bookkeeping are parent-owned; errors/interrupts propagate after
cleanup without leaving this call's reservations RUNNING.
| PARAMETER | DESCRIPTION |
|---|---|
model_creator
|
TYPE:
|
search_space
|
TYPE:
|
data_loader
|
Returns 3D tensors keyed
TYPE:
|
n_trials
|
Positive count of NEW attempted configurations; transferred scores do not consume this budget. Resume adds this many attempts.
TYPE:
|
loss
|
Raw forecast objective. Built-in/default losses minimize. |
loss_params
|
Keyword options forwarded to the raw forecast objective.
TYPE:
|
targets_key
|
Name of the target readout.
TYPE:
|
drivers_keys
|
Declared driver data suffixes.
TYPE:
|
monitor_losses
|
Additional final-horizon losses, recorded without changing the objective. |
monitor_params
|
Additional final-horizon losses, recorded without changing the objective. |
study_name
|
In-memory by default, or an explicit journal/SQLite study. Only the parent opens storage, so in-memory studies work with multiple workers.
TYPE:
|
storage
|
In-memory by default, or an explicit journal/SQLite study. Only the parent opens storage, so in-memory studies work with multiple workers.
TYPE:
|
warm_start
|
Enqueue fixed settings for evaluation, preserving unsuggested values. |
transfer_from
|
Prior study or a path containing exactly one study. Full configurations are re-evaluated by default; source provenance is recorded.
TYPE:
|
sampler
|
Parent-owned sampling/pruning. Pruning at streamed horizon checkpoints stops future forecast generation; raw prefix scoring can retain history.
TYPE:
|
pruner
|
Parent-owned sampling/pruning. Pruning at streamed horizon checkpoints stops future forecast generation; raw prefix scoring can retain history.
TYPE:
|
seed
|
Trial initialization seed is seed + trial.number. Caller RNG streams are restored; the post-data-loading RNG sequence reaches the worker.
TYPE:
|
device
|
Numerical model/data device. Parameter/scoring operations stay there when supported, with the existing NumPy custom-loss fallback. |
n_workers
|
Positive joblib worker count; one runs in the caller.
TYPE:
|
verbosity
|
Zero is quiet. Caller logging levels are restored after this call.
TYPE:
|
catch_exceptions
|
Record invalid evaluation attempts rather than aborting on their error.
TYPE:
|
penalty_value
|
Explicit numeric failure penalty when
TYPE:
|
clip_value
|
Optional upper bound on a completed trial loss.
TYPE:
|
prune_on_clip
|
Prune a trial when its loss reaches
TYPE:
|
horizon_key
|
Data key specifying the forecast length; cannot exceed validation truth.
TYPE:
|
n_checkpoints
|
Growing forecast prefixes; reports use 1-based checkpoint indices.
TYPE:
|
torch_scoring
|
Prefer on-device numeric scoring until the final scalar.
TYPE:
|
trial_callbacks
|
Parent callbacks receive the real Trial and params/raw_loss/loss. TrialPruned propagates; other callback errors are logged/ignored. |
error_policy
|
Invalid evaluation representation. Penalty results are never valid winners.
TYPE:
|
transfer_mode
|
Copy evaluated scores only for identical bound task/objective protocols.
TYPE:
|
task_context
|
Explicit trusted version/content identity for external data/resources. Prior materialized data is checked before old scores can win. Callbacks requiring a live study on replay need this explicit assertion.
TYPE:
|
inner_max_num_threads
|
joblib worker thread limit; caller thread settings remain unchanged.
TYPE:
|
memory_budget
|
Estimated-memory admission and reduced numerical concurrency. An arbitrary raw factory requires a custom estimator. Oversized candidates are PRUNED before model construction; raw prefix storage is included in the known minimum. These estimates do not impose a process/RAM limit.
TYPE:
|
memory_estimator
|
Estimated-memory admission and reduced numerical concurrency. An arbitrary raw factory requires a custom estimator. Oversized candidates are PRUNED before model construction; raw prefix storage is included in the known minimum. These estimates do not impose a process/RAM limit.
TYPE:
|
Source code in src/resdag/hpo/run.py
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 | |
Raw execution and pruning¶
Raw forecasts are generated in chunks. Each growing-prefix report reaches the
parent pruner before later chunks are generated. A rejection stops future
forecast generation. n_checkpoints=5 requests five checkpoints by default;
short horizons can yield fewer distinct checkpoints.
The raw losses retain their existing prefix-dependent normalization, so raw
scoring can retain a complete prediction prefix: O(horizon) storage. Custom
and monitor losses receive full-horizon tensors when an evaluation completes.
With torch_scoring=True, supported losses stay on the tensor device until their
final scalar; custom losses may use the NumPy fallback. Attractor-dimension
scoring uses NumPy.
Registry keys are "none", "median", "asha", "hyperband" and "threshold".
Raw defaults are minimization losses; choose a configured pruner with suitable
bounds for a custom metric. clip_value/prune_on_clip is a separate raw-loss
ceiling and can be combined with a pruner. The common tuner's positive threshold
preset is not the raw preset.
memory_budget accepts the same MemoryBudget, size string or byte count.
An arbitrary raw factory requires memory_estimator(params, context) when a
budget is set. Known prepared data, transfers and retained output storage form
a minimum; oversized candidates are PRUNED before factory construction.
Parent data preparation happens before estimation, and a pending configuration
may remain resident while an admitted window runs. This is planning, not a hard
process/RSS/device limit. See tuning resources.
inner_max_num_threads=1 limits native threads in numerical worker processes.
The parent environment, thread settings, logging and Python/NumPy/Torch RNG
streams are preserved/restored. seed initializes the sampler and each trial's
seed + trial.number RNG scope. Make the factory accept and forward a seed
keyword; an explicit model seed in resolved settings takes precedence. Forwarding
it also controls initializers with their own local generators. Adaptive proposals
can change with worker count and scheduling; exact reproducibility is not a
cross-device or cross-schedule guarantee.
Reuse and transfer¶
run_hpo(..., warm_start=[config]) queues explicit settings.
run_hpo(..., transfer_from=source) queues complete valid settings from a study
or storage path for reevaluation by default. Data-only suggestions and fixed
model values are preserved. Single-objective configurations are ordered best
first, then by trial number; multi-objective sources retain source order.
Use export_best_config(study) when fixed returned values matter;
study.best_params contains only Optuna suggestions. Incompatible model settings
must be adapted explicitly. Source study/trial/protocol provenance is retained
under the trial's resdag_transfer attribute.
transfer_mode="scores" requires exactly matching bound task protocols and
objective directions. Raw resumption and score import replay historical data
preparation with Optuna FixedTrial and check the actual prepared tensor
contents. A file changed at the same path is therefore a changed task. Callbacks
can run again during validation; keep preparation free of side effects.
When historical preparation cannot run without live-study resources, supply
task_context="dataset-v3" or portable metadata. This explicitly asserts the
identity of opaque resources, so update it when they change. Successful replay
still checks tensor contents. New attempts receive a real Optuna trial.
Use settings reevaluation for changed experiments rather than copying scores.
transfer
¶
Reuse complete settings by re-evaluating them on a destination task.
Copying completed scores is an explicit operation restricted to matching bound task protocols and objective directions. Transfer preserves full settings, suggestions, and source-study provenance; it never filters a scored model.
transfer_trials
¶
transfer_trials(
study: Study,
transfer_from: Study | str,
*,
mode: Literal["reevaluate", "scores"] = "reevaluate",
protocol_hash: str | None = None
) -> int
Reuse complete configurations, re-evaluating them by default.
mode="reevaluate" enqueues full recorded resolved settings, including
fixed values that were not Optuna suggestions. Old scores are not copied.
Source study/trial/protocol provenance is retained on every queued trial.
A changed objective direction is allowed because the new task evaluates
the settings again. No parameter is silently removed to fit a new space.
mode="scores" imports finite completed values only when both studies
are bound to exactly protocol_hash and their directions match. The
caller's protocol must identify actual data, validation, objective and
construction settings. An unbound or changed task must re-evaluate instead.
All source parameters/distributions and complete resolved settings remain
intact; incompatible model settings should be adapted explicitly before
enqueueing, never combined with an old score.
Returns the number of queued or copied configurations. Invalid/nonfinite source evaluations are skipped. Caller-owned study connections are not closed; a source opened from a path is released on success and failure.
Source code in src/resdag/hpo/transfer.py
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 | |
apply_warm_start
¶
Enqueue known-good configurations ahead of sampler-proposed trials.
Each mapping in warm_start is enqueued via
optuna.study.Study.enqueue_trial, which guarantees the configuration
is the next one handed to the objective — i.e. it runs before any trial
the sampler would otherwise propose. The parent enqueues settings before preparing finite numerical job windows.
Queued fixed values remain available even when the current search-space
function does not suggest them.
| PARAMETER | DESCRIPTION |
|---|---|
study
|
The study to enqueue trials into.
TYPE:
|
warm_start
|
Each dict maps parameter name to a fixed value. Empty or
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
int
|
The number of configurations enqueued. |
Examples:
>>> apply_warm_start(study, [{"reservoir_size": 300, "spectral_radius": 0.9}])
1
Source code in src/resdag/hpo/transfer.py
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 | |
export_best_config
¶
Export a study's best parameters as a reusable warm_start entry.
Returns the best completed trial's parameters as a plain dict that can
be dropped straight into the warm_start list of a later
resdag.hpo.run_hpo call, letting the winner of one run seed the
next.
| PARAMETER | DESCRIPTION |
|---|---|
study
|
A study with at least one
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Complete recorded resolved settings, including fixed factory values. External studies without that record fall back to their suggestions. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the study has no completed trials. |
Examples:
>>> best = export_best_config(study)
>>> run_hpo(..., warm_start=[best])
Source code in src/resdag/hpo/transfer.py
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 | |
Study ownership and inspection¶
Owned RDB sessions and persistent connection pools are released after success or failure, including setup failures. Returned studies remain usable and reconnect when needed. SQLite memory pools remain alive while their returned study needs them. Caller-owned studies retain their connections/ownership. Cleanup errors preserve an already-active original error and add a note; otherwise the cleanup error is raised.
A source storage path must contain exactly one study; pass an explicit source
study to choose among several. Transfer excludes incomplete, invalid and
nonfinite evaluations; exact-score imports preserve matching finite objective
vectors. get_study_summary orders valid results according to study direction.
Resource policies and helpers¶
MemoryContext is the immutable public input to a custom memory_estimator.
Tuning supplies shapes, placement, retained storage and recognized execution
layout; the callback returns a MemoryEstimate or a byte count. For separate
planning, construct a context from known facts and call estimate_memory.
The preparation-specific context builders are implementation details.
Estimates guide admission and concurrency; they are not process or allocator
limits and do not change model precision or device policy.
resources
¶
Optional planning estimates and staged screening for model tuning.
These helpers never inspect or change process limits, allocator settings or model precision. Byte estimates guide admission and concurrency; they are not operating-system, resident-memory or accelerator-allocation limits.
Screening
dataclass
¶
Screening(
seed_count: int = 1,
origin_count: int = 1,
keep_fraction: float = 1 / 3,
cohort_size: int | None = None,
)
Evaluate a cohort cheaply, then reevaluate its best fraction in full.
Screening is opt-in. The default None uses all configured seeds and
origins for every candidate. With balanced tuning, this default screen
checks all 24 candidates on one seed/origin, then promotes the best eight.
cohort_size=None uses the entire new-trial budget as one cohort.
validate
¶
Reject a screen that asks for more repetitions than full evaluation.
Source code in src/resdag/hpo/resources.py
118 119 120 121 122 123 | |
promoted_count
¶
Round promotion upward; a nonempty cohort always retains a candidate.
Source code in src/resdag/hpo/resources.py
125 126 127 128 129 | |
MemoryBudget
dataclass
¶
MemoryBudget(
limit: int | str,
device_limit: int | str | None = None,
worker_overhead: int | str = "256MiB",
)
Admission budget for estimated host/device peaks and worker overhead.
limit bounds their sum. device_limit adds a device-only bound.
Decimal GB and binary GiB are distinct. Values are parsed to integer bytes
once. This never sets an OS, RSS, process or accelerator allocator limit.
device_limit_bytes
property
¶
device_limit_bytes: int | None
The optional parsed accelerator-only limit.
worker_overhead_bytes
property
¶
worker_overhead_bytes: int
Host overhead reserved per admitted candidate.
fits
¶
fits(estimate: MemoryEstimate, current: Sequence[MemoryEstimate] = ()) -> bool
Whether adding a candidate fits alongside all active estimates.
Each candidate, including the first, adds worker_overhead host
bytes. Call with an empty current to reject an oversized candidate
before construction; otherwise wait/reduce concurrency until it fits.
Source code in src/resdag/hpo/resources.py
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 | |
MemoryEstimate
dataclass
¶
Estimated peak bytes for one candidate, including its final full refit.
host_bytes and device_bytes are separate planning accounts. A custom
estimator owns their accuracy. Details are detached immutable metadata.
MemoryContext
dataclass
¶
MemoryContext(
input_shapes: Mapping[str, tuple[int, ...]],
target_shapes: Mapping[str, tuple[int, ...]],
dtype: dtype,
device: device,
train_samples: int,
refit_samples: int,
dataset_host_bytes: int,
dataset_device_bytes: int,
model_host_bytes: int,
model_device_bytes: int,
readout_features: tuple[int, ...],
readout_outputs: tuple[int, ...],
activation_width: int,
max_horizon: int,
preset_options: Mapping[str, Any] = dict(),
retained_forecast_bytes: int = 0,
replay_history_bytes: int = 0,
forecast_samples: int = 0,
readout_train_samples: tuple[int, ...] = (),
readout_refit_samples: tuple[int, ...] = (),
sequence_layout: Mapping[str, Any] = dict(),
)
Immutable shapes/storage facts for resource estimation; no live objects.
Sample counts cover complete observation prefixes, including washout. The
final refit is therefore included even when validation fits are shorter.
Storage counts deduplicate aliases within the dataset and within the model.
Optional readout_*_samples describe fitted rows after washout and any
built-in batch expansion; the observation counts above keep their original
meaning. sequence_layout contains detached immutable shape facts for
recognized built-in execution only. Empty defaults preserve the generic
estimate and existing custom-estimator contracts.
estimate_memory
¶
estimate_memory(
params: Mapping[str, Any],
context: MemoryContext,
*,
custom_factory: bool = False,
estimator: (
Callable[[dict[str, Any], MemoryContext], MemoryEstimate | int] | None
) = None
) -> MemoryEstimate
Estimate peak fit/forecast/refit bytes, before candidate construction.
Automatic planning reserves dense preset weights, retained/staged model copies, full-refit feature traces and 8-byte QR/SVD/Gram workspaces. On an accelerator it also reserves a CPU solve bridge. This deliberately favors overestimation; custom layers and factories should provide their own estimator. A custom result is a complete estimate, not an added surcharge; it cannot remove known resident dataset/model or retained-prefix storage.
Source code in src/resdag/hpo/resources.py
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 | |
Raw losses¶
losses
¶
Loss functions for hyperparameter optimization.
This module provides specialized loss functions for evaluating multi-step
forecasts in reservoir computing applications. All functions operate on
batched predictions with shape (B, T, D) where B is batch size, T is
time steps, and D is the number of dimensions.
Available Losses
"efh": Expected Forecast Horizon (default, recommended for chaotic systems)"forecast_horizon": Forecast Horizon Loss (contiguous valid steps)"lyapunov": Lyapunov-weighted Loss (exponential decay for chaotic systems)"standard": Standard Loss (mean geometric mean error)"soft_horizon": Soft valid horizon (cumulative survival probability)"attractor_dimension": Attractor-fidelity — correlation-dimension mismatch of the forecast vs the truth (climate reconstruction, not short-horizon error)
Scale conventions
The threshold-based horizon losses (expected_forecast_horizon,
forecast_horizon, soft_valid_horizon) compare a per-timestep
error against a fixed threshold. For that comparison to be meaningful the
error metric must be scale-free, otherwise the same threshold collapses the
horizon to 0 or T depending on the absolute scale of the data. All of
these losses therefore default to metric="nrmse" (RMSE normalised by the
per-dimension standard deviation of y_true). Selecting a raw-scale metric
("rmse", "mse", "mae") for a threshold-based loss emits a
UserWarning, because the threshold is then only valid on
unit-scale data.
Batch aggregation
Per-timestep errors of shape (B, T) are collapsed across the batch axis
with the median in every loss (see _aggregate_batch). The median
is robust to outlier trajectories and — unlike the geometric mean — does not
collapse to 0 when a single batch element happens to be perfect at a step.
When a geometric mean is requested explicitly it is computed on
clipped errors so it is zero-safe.
Example
from resdag.hpo import LOSSES, get_loss loss_fn = get_loss("efh") loss = loss_fn(y_true, y_pred, threshold=0.2)
See Also
resdag.hpo.objective : Objective builder that wraps these losses for Optuna. resdag.hpo.run : High-level HPO orchestrator.
LOSSES
module-attribute
¶
LOSSES: dict[str, Callable[..., float]] = {
"efh": expected_forecast_horizon,
"forecast_horizon": forecast_horizon,
"lyapunov": lyapunov_weighted,
"standard": standard_loss,
"soft_horizon": soft_valid_horizon,
"attractor_dimension": attractor_dimension_error,
}
LossProtocol
¶
Bases: Protocol
Protocol for HPO loss functions.
All loss functions must accept y_true and y_pred arrays of shape
(B, T, D) as positional-only arguments and return a single float
value to minimize.
Examples:
Implementing a custom loss:
>>> def my_loss(y_true, y_pred, /, **kwargs):
... return float(np.mean((y_true - y_pred) ** 2))
get_loss
¶
get_loss(key_or_callable: str | LossProtocol) -> LossProtocol
Get a loss function by key or return the callable directly.
| PARAMETER | DESCRIPTION |
|---|---|
key_or_callable
|
Either a string key from LOSSES (e.g., "efh") or a custom callable following the LossProtocol interface. |
| RETURNS | DESCRIPTION |
|---|---|
LossProtocol
|
The loss function callable. |
| RAISES | DESCRIPTION |
|---|---|
KeyError
|
If the string key is not found in LOSSES. |
TypeError
|
If the provided callable doesn't match LossProtocol. |
Example
loss_fn = get_loss("efh") loss_fn = get_loss(my_custom_loss)
Source code in src/resdag/hpo/losses.py
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 | |
expected_forecast_horizon
¶
expected_forecast_horizon(
y_true: NDArray[floating],
y_pred: NDArray[floating],
/,
metric: MetricType = "nrmse",
threshold: float = 0.2,
softness: float = 0.04,
) -> float
Differentiable proxy for forecast horizon length.
This is the recommended loss for chaotic systems. It provides a smooth, differentiable approximation of the forecast horizon by using a soft threshold. The loss rewards models that keep errors below the threshold for as many consecutive steps as possible.
| PARAMETER | DESCRIPTION |
|---|---|
y_true
|
True values of shape (B, T, D).
TYPE:
|
y_pred
|
Predicted values of shape (B, T, D).
TYPE:
|
metric
|
Error metric:
TYPE:
|
threshold
|
Error threshold below which predictions are considered "good".
TYPE:
|
softness
|
Controls the width of the soft threshold boundary. Smaller values
create a harder threshold. The default is
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
Negative expected forecast horizon. Lower (more negative) is better. |
| WARNS | DESCRIPTION |
|---|---|
UserWarning
|
If metric is not scale-free (i.e. not |
Source code in src/resdag/hpo/losses.py
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 | |
forecast_horizon
¶
forecast_horizon(
y_true: NDArray[floating],
y_pred: NDArray[floating],
/,
metric: MetricType = "nrmse",
threshold: float = 0.2,
) -> float
Contiguous valid forecast horizon length.
Counts the number of consecutive time steps where the error stays below the threshold, starting from the beginning of the forecast.
| PARAMETER | DESCRIPTION |
|---|---|
y_true
|
True values of shape (B, T, D).
TYPE:
|
y_pred
|
Predicted values of shape (B, T, D).
TYPE:
|
metric
|
Error metric:
TYPE:
|
threshold
|
Error threshold below which predictions are considered valid.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
Negative of the valid horizon length. Lower is better. |
| WARNS | DESCRIPTION |
|---|---|
UserWarning
|
If metric is not scale-free (i.e. not |
Source code in src/resdag/hpo/losses.py
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 | |
lyapunov_weighted
¶
lyapunov_weighted(
y_true: NDArray[floating],
y_pred: NDArray[floating],
/,
metric: MetricType = "nrmse",
lyapunov_t: int = 64,
) -> float
Lyapunov-compensated time-weighted error.
Computes a time-weighted error where weights decay exponentially with characteristic time equal to the Lyapunov time. This compensates for expected exponential error growth in chaotic systems by applying a weight of exp(-t / lyapunov_t) at time step t.
At t = lyapunov_t, the weight equals exp(-1).
| PARAMETER | DESCRIPTION |
|---|---|
y_true
|
True values of shape (B, T, D).
TYPE:
|
y_pred
|
Predicted values of shape (B, T, D).
TYPE:
|
metric
|
Per-step error metric:
TYPE:
|
lyapunov_t
|
Characteristic Lyapunov time (in time steps) controlling the exponential decay rate of the weights.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
Exponentially time-weighted average error. Lower is better. |
Notes
Errors are reduced across the batch with a zero-safe geometric mean
(clipped to a small positive floor; see _aggregate_batch).
Source code in src/resdag/hpo/losses.py
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 | |
standard_loss
¶
standard_loss(
y_true: NDArray[floating],
y_pred: NDArray[floating],
/,
metric: MetricType = "nrmse",
) -> float
Mean geometric mean error across all timesteps.
Simple baseline loss suitable for both stable and unstable systems.
| PARAMETER | DESCRIPTION |
|---|---|
y_true
|
True values of shape (B, T, D).
TYPE:
|
y_pred
|
Predicted values of shape (B, T, D).
TYPE:
|
metric
|
Error metric:
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
Mean of geometric mean errors. Lower is better. |
Notes
The geometric mean across the batch is zero-safe: errors are clipped to a
small positive floor before reduction (see _aggregate_batch) so a
single perfect batch element cannot collapse a step to 0.
Source code in src/resdag/hpo/losses.py
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 | |
soft_valid_horizon
¶
soft_valid_horizon(
y_true: NDArray[floating],
y_pred: NDArray[floating],
/,
metric: MetricType = "nrmse",
threshold: float = 0.3,
n: int = 6,
) -> float
Soft forecast horizon via cumulative survival probability.
At each timestep a soft indicator measures how "good" the prediction is using a Hill-function gate:
where \(e_t\) is the median error at step t, \(\theta\) is the threshold, and n controls the sharpness. A cumulative product of these indicators gives a survival probability that drops to zero once any step fails, mimicking a contiguous forecast horizon:
The function is numerically safe: error ratios are clipped before exponentiation to prevent overflow.
| PARAMETER | DESCRIPTION |
|---|---|
y_true
|
True values of shape (B, T, D).
TYPE:
|
y_pred
|
Predicted values of shape (B, T, D).
TYPE:
|
metric
|
Per-step error metric:
TYPE:
|
threshold
|
Error threshold below which predictions are considered "good".
TYPE:
|
n
|
Hill exponent controlling gate sharpness. Lower values (4-8) give smoother landscapes suitable for TPE optimisation; higher values (>12) approach a hard step function with poor gradient signal.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
Negative expected horizon. Lower (more negative) is better. |
| WARNS | DESCRIPTION |
|---|---|
UserWarning
|
If metric is not scale-free (i.e. not |
Notes
Compared to expected_forecast_horizon (which uses a sigmoid gate
and batch-median), this loss uses a Hill-function gate and batch-median.
The Hill gate has a sharper but still tunable transition and is symmetric
around the threshold on a log-error scale.
See Also
expected_forecast_horizon : Sigmoid-gated variant with cumprod survival.
Source code in src/resdag/hpo/losses.py
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 | |
attractor_dimension_error
¶
attractor_dimension_error(
y_true: NDArray[floating],
y_pred: NDArray[floating],
/,
max_points: int = 2000,
n_bins: int = 20,
fit_window: tuple[float, float] = (0.1, 0.5),
seed: int = 0,
) -> float
Attractor-fidelity loss: correlation-dimension mismatch of the forecast.
Scores how well a free-running forecast reproduces the true system's
climate — the long-run geometry of its attractor — rather than its
short-horizon pointwise accuracy. It is the absolute difference of the
Grassberger-Procaccia correlation dimension (resdag.metrics. correlation_dimension) of the forecast and of the truth:
A forecast that has rebuilt the right attractor matches the truth's fractal
dimension even after the pointwise trajectory has decorrelated, so this loss
keeps rewarding a model long past the valid-prediction horizon — exactly the
regime the threshold-based horizon losses (expected_forecast_horizon,
forecast_horizon) go blind in. Optimise it (or monitor it
alongside a horizon loss) to select for climate / attractor fidelity, not
just a few Lyapunov times of tracking.
Because it depends only on the geometry of each trajectory, the two inputs
need not be time-aligned; each (T, D) trajectory is embedded and its
dimension estimated independently. A long enough forecast window is required
for the correlation-sum scaling region to exist (a few thousand steps for a
3-D chaotic system).
| PARAMETER | DESCRIPTION |
|---|---|
y_true
|
Ground-truth trajectory of shape
TYPE:
|
y_pred
|
Forecast trajectory of shape
TYPE:
|
max_points
|
Cap on the points used per dimension estimate (the pair count is \(O(M^2)\)); longer trajectories are subsampled.
TYPE:
|
n_bins
|
Number of log-spaced radii in the correlation sum.
TYPE:
|
fit_window
|
Scaling region (as fractions of the log-radius span) over which the \(\log C\) vs \(\log r\) slope is fit.
TYPE:
|
seed
|
Seed for the subsampling draw, so the loss is deterministic.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
\(|D_2(\hat y) - D_2(y)|\ge 0\). Lower is better; |
Notes
This is a monitor-friendly fidelity score, not a smooth differentiable
proxy: the correlation dimension is a slope estimate and can be noisy on a
short window, so it pairs best as a monitor_losses entry in
resdag.hpo.run_hpo (logged but not optimised), or as the optimised
objective when the study explicitly targets climate reconstruction.
See Also
resdag.metrics.correlation_dimension : The underlying dimension estimator. lyapunov_weighted : A complementary time-weighted pointwise loss.
Source code in src/resdag/hpo/losses.py
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 | |
Study utilities¶
utils
¶
Utility functions for hyperparameter optimization.
Provides helpers for study management, naming, and result summarization.
See Also
resdag.hpo.run : High-level HPO orchestrator that uses these utilities.
get_study_summary
¶
Generate a human-readable summary of an Optuna study.
Creates a formatted text summary including study statistics, best trial information, and top N trials ranked in the study's objective direction.
| PARAMETER | DESCRIPTION |
|---|---|
study
|
The Optuna study to summarize.
TYPE:
|
top_n
|
Number of top-performing trials to include.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
Formatted multi-line summary string. |
Example
study = optuna.create_study()
... run optimization ...¶
print(get_study_summary(study))
Source code in src/resdag/hpo/utils.py
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 | |
make_study_name
¶
Generate a stable study name from the model creator callable.
Creates a study name based on the callable's source file and name. It is robust to callables that lack the usual introspection metadata:
functools.partialobjects are unwrapped to their underlying function so the wrapped factory's name and source file are used (a barepartialraisesTypeErrorininspect.getsourcefile).- Callables without a usable
__name__(e.g. lambdas or callable class instances) fall back to their type name plus a short stable hash of theirrepr, so two logically-distinct creators do not collide onto the same study name and silently share persisted storage.
| PARAMETER | DESCRIPTION |
|---|---|
model_creator
|
The model creator callable to generate a name from. May be a plain
function, a
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
Study name in the format |
Example
def my_model_creator(units): ... return model make_study_name(my_model_creator) 'script:my_model_creator'
Source code in src/resdag/hpo/utils.py
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 | |
get_best_params
¶
get_best_params(study: Study) -> dict
Get the best parameters from a study.
Convenience function that returns the best trial's parameters.
| PARAMETER | DESCRIPTION |
|---|---|
study
|
The Optuna study.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Dictionary of best hyperparameters. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If no completed trials exist. |
Source code in src/resdag/hpo/utils.py
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 | |