Skip to content

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
def 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: optuna.samplers.BaseSampler | None = None,
    pruner: str | optuna.pruners.BasePruner | None = None,
    checkpoint_interval: int = 64,
    study: optuna.Study | None = None,
    storage: str | None = None,
    study_name: str | None = None,
    warm_start: optuna.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.
    """
    started = time.perf_counter()
    if preset not in _PRESETS:
        raise ValueError("preset must be 'quick', 'balanced' or 'thorough'")
    if factory is not None and isinstance(model, ESN):
        raise ValueError("ESN rebuilds itself automatically; use rd.Model for a custom factory")
    if aggregation not in ("weakest", "mean"):
        raise ValueError("aggregation must be 'weakest' or 'mean'")
    if execution not in ("auto", "fast", "history"):
        raise ValueError("execution must be 'auto', 'fast' or 'history'")
    if direction not in ("maximize", "minimize"):
        raise ValueError("direction must be 'maximize' or 'minimize'")
    if objective is None and direction != "maximize":
        raise ValueError("The built-in horizon objective requires direction='maximize'")
    if not math.isfinite(threshold) or threshold <= 0:
        raise ValueError("threshold must be positive and finite")
    if timeout is not None and (not math.isfinite(timeout) or timeout <= 0):
        raise ValueError("timeout must be positive and finite")
    if isinstance(n_jobs, bool) or not isinstance(n_jobs, int) or n_jobs == 0:
        raise ValueError("n_jobs must be a nonzero integer")
    _count(inner_max_num_threads, "inner_max_num_threads")
    _count(checkpoint_interval, "checkpoint_interval")
    if not isinstance(catch_exceptions, bool):
        raise TypeError("catch_exceptions must be a boolean")
    if isinstance(seed, bool) or not isinstance(seed, int) or not 0 <= seed < 2**63:
        raise ValueError("seed must be an integer in [0, 2**63)")
    trials, seed_count, origin_count = _PRESETS[preset]
    trials = trials if n_trials is None else _count(n_trials, "n_trials")
    origin_count = origin_count if n_origins is None else _count(n_origins, "n_origins")
    fixed_graph = factory is None and _automatic_options(model) is None
    if seeds is None:
        seeds = tuple(seed + i for i in range(1 if fixed_graph else seed_count))
    try:
        seeds = tuple(seeds)
    except TypeError as error:
        raise ValueError("seeds must be a nonempty sequence of integers") from error
    if not seeds or any(
        isinstance(s, bool) or not isinstance(s, int) or not 0 <= s < 2**63 for s in seeds
    ):
        raise ValueError("seeds must contain integers in [0, 2**63)")
    seed_bank = tuple(dict.fromkeys(seeds))
    if fixed_graph and len(seed_bank) != 1:
        raise ValueError("Several initialization seeds require a factory to rebuild a custom DAG")
    if study is not None and (
        storage is not None or study_name is not None or sampler is not None or pruner is not None
    ):
        raise ValueError("Pass an existing study or storage/study_name/sampler/pruner, not both")
    if warm_start is not None and not isinstance(warm_start, optuna.Study):
        raise TypeError("warm_start must be an Optuna study")
    if warm_start is not None and warm_start is study:
        raise ValueError("warm_start must be a separate source study")
    if transfer_mode not in ("reevaluate", "scores"):
        raise ValueError("transfer_mode must be 'reevaluate' or 'scores'")
    if search_space is not None and not callable(search_space):
        raise TypeError("search_space must be callable")
    if factory is not None and not callable(factory):
        raise TypeError("factory must be callable")
    if objective is not None and not callable(objective):
        raise TypeError("objective must be callable")
    if pruning_objective is not None and not callable(pruning_objective):
        raise TypeError("pruning_objective must be callable")
    if screening is True:
        screening = Screening()
    elif screening is False:
        screening = None
    elif screening is not None and not isinstance(screening, Screening):
        raise TypeError("screening must be False, True, or a Screening policy")
    budget = (
        memory_budget
        if isinstance(memory_budget, MemoryBudget) or memory_budget is None
        else MemoryBudget(memory_budget)
    )
    if memory_estimator is not None and not callable(memory_estimator):
        raise TypeError("memory_estimator must be callable")
    if memory_estimator is not None and budget is None:
        raise ValueError("memory_estimator requires memory_budget")
    if budget is not None and factory is not None and memory_estimator is None:
        raise ValueError("A custom factory with a memory budget requires memory_estimator")
    resolved_pruner: optuna.pruners.BasePruner
    if study is None and isinstance(pruner, str) and pruner.lower() == "threshold":
        if objective is not None:
            raise ValueError(
                "The common threshold preset is for positive horizon scores; "
                "supply a configured Optuna ThresholdPruner for a custom objective"
            )
        resolved_pruner = optuna.pruners.ThresholdPruner(
            lower=0.1, n_warmup_steps=2 * checkpoint_interval
        )
    else:
        resolved_pruner = resolve_pruner(pruner) if study is None else study.pruner
    # A huge lazy preset must not allocate its initial dense recurrence before
    # resource planning can even start. This is a known lower bound, not a
    # substituted smaller architecture or a claim about solver peak memory.
    if budget is not None and isinstance(model, ESN) and model.workflow is None:
        size = model._factory_options["reservoir_size"]
        sample = training.get("input") if isinstance(training, Mapping) else training
        if is_trajectory(sample):
            sample = torch.as_tensor(cast(Any, sample).y)
        element = model._reference.element_size()
        if not model._dtype_pinned and isinstance(sample, torch.Tensor):
            element = sample.element_size()
        lower = size * size * element
        destination = (
            model._reference.device
            if model._device_pinned or not isinstance(sample, torch.Tensor)
            else sample.device
        )
        minimum = MemoryEstimate(lower) if destination.type == "cpu" else MemoryEstimate(0, lower)
        if not budget.fits(minimum):
            raise ValueError(
                "The lazy ESN base template exceeds memory_budget before construction; "
                "start from a smaller base model or provide a custom construction recipe"
            )
    previous_report = model.__dict__.get("tuning_report")
    resuming = isinstance(previous_report, TuningReport) and (
        study is previous_report.study
        or (storage is not None and study_name == previous_report.study.study_name)
    )
    if resuming:
        assert isinstance(previous_report, TuningReport)
        if _model_hash(model) != previous_report._installed_hash:
            raise ValueError(
                "The model changed since tuning; use a fresh study for a changed model"
            )
        template = _template(previous_report._template, training, seed)
    else:
        template = _template(model, training, seed)
    workflow = _workflow(template)
    data = prepare_tuning_data(
        workflow,
        training,
        targets,
        validation=validation,
        validation_fraction=validation_fraction,
        horizon=horizon,
        n_origins=origin_count,
    )
    if screening is not None:
        screening.validate(len(seed_bank), len(data.origins))
    memory = (
        None
        if budget is None
        else _memory_context(
            workflow,
            data,
            preset_options=_automatic_options(template),
        )
    )
    if memory is not None and (objective is not None or pruning_objective is not None):
        reference = module_reference(workflow.graph)
        element = 4 if reference is None else reference.element_size()
        batch = next(iter(data.origins[0].truth.values()))
        batches = batch.shape[0] if batch.ndim == 3 else 1
        retained = (
            batches
            * max(origin.horizon for origin in data.origins)
            * sum(workflow._output_widths)
            * element
        )
        memory = replace(memory, retained_forecast_bytes=retained)
    if memory is not None and (
        execution == "history" or (execution == "auto" and workflow._requires_complete_history())
    ):
        element = torch.finfo(memory.dtype).bits // 8
        replay = max(
            sum(
                (value.shape[0] if value.ndim == 3 else 1)
                * (value.shape[-2] + origin.horizon)
                * value.shape[-1]
                for value in origin.history.values()
            )
            for origin in data.origins
        )
        memory = replace(
            memory,
            replay_history_bytes=3 * element * replay,
            forecast_samples=max(
                (value.shape[0] if value.ndim == 3 else 1) * (value.shape[-2] + origin.horizon)
                for origin in data.origins
                for value in origin.history.values()
            ),
        )
    automatic = _automatic_options(template)
    recipe = factory or (
        _preset_recipe(template) if automatic is not None else _fixed_recipe(template)
    )
    space = search_space or _default_space(template)
    fingerprint, _ = _protocol(
        data,
        template,
        seeds=seed_bank,
        threshold=threshold,
        aggregation=aggregation,
        direction=direction,
        factory=_callable_identity(factory),
        search_space=_callable_identity(search_space),
        objective=_callable_identity(objective),
        pruning_objective=_callable_identity(pruning_objective),
        memory_budget=None if budget is None else asdict(budget),
        memory_estimator=_callable_identity(memory_estimator),
        fixed_graph=fixed_graph,
        builtin_recipe=(
            None
            if automatic is None
            else {
                "version": 1,
                "family": cast(dict[str, Any], builtin_recipe(template.graph))["family"],
                "options": _configuration(automatic),
                "default_space_version": 2 if search_space is None else None,
            }
        ),
        execution=execution,
    )
    owned = None
    primary_error: BaseException | None = None
    try:
        if study is None:
            owned = resolve_storage(storage, n_workers=1)
            study = optuna.create_study(
                storage=owned,
                study_name=study_name,
                load_if_exists=study_name is not None,
                direction=direction,
                sampler=sampler or optuna.samplers.TPESampler(seed=seed),
                pruner=resolved_pruner,
            )
        if len(study.directions) != 1 or study.direction.name.lower() != direction:
            raise ValueError("Study direction must match the tuning objective")
        bind_protocol(study, fingerprint)
        if warm_start is not None:
            from .transfer import transfer_trials

            transfer_trials(study, warm_start, mode=transfer_mode, protocol_hash=fingerprint)
        study.set_user_attr(
            "resdag_tuning",
            {
                "version": 2,
                "seeds": list(seed_bank),
                "refit_seed": seed_bank[0],
                "validation": data.report,
                "threshold": threshold,
                "aggregation": aggregation,
                "direction": direction,
                "fixed_graph": fixed_graph,
            },
        )
        reference = module_reference(workflow.graph)
        evaluator = _Evaluator(
            recipe,
            data,
            seed_bank,
            threshold,
            aggregation,
            objective,
            catch_exceptions,
            torch.device("cpu") if reference is None else reference.device,
            execution,
            checkpoint_interval,
            pruning_objective,
        )
        attempts, resource_report = _run_trials(
            study,
            evaluator,
            space,
            trials=trials,
            seed=seed,
            n_jobs=n_jobs,
            inner_max_num_threads=inner_max_num_threads,
            started=started,
            timeout=timeout,
            direction=direction,
            screening=screening,
            budget=budget,
            context=memory,
            custom_factory=factory is not None,
            estimator=memory_estimator,
        )
        study.set_user_attr("resdag_tuning_resources", resource_report)
        valid = [
            trial
            for trial in study.trials
            if trial.state == optuna.trial.TrialState.COMPLETE
            and trial.user_attrs.get("resdag_tune_valid")
            and trial.value is not None
            and math.isfinite(trial.value)
        ]
        if not valid:
            detail = next(
                (
                    trial.user_attrs.get("error", trial.user_attrs.get("pruning_reason"))
                    for trial in study.trials
                    if "error" in trial.user_attrs or "pruning_reason" in trial.user_attrs
                ),
                "no evaluation finished",
            )
            raise RuntimeError(f"No valid tuning candidates completed: {detail}")
        best = (max if direction == "maximize" else min)(
            valid, key=lambda trial: cast(float, trial.value)
        )
        if study.best_trial.number != best.number:
            raise ValueError(
                "Study contains a winning score outside this tuning protocol; use a fresh study"
            )
        best_params = ast.literal_eval(best.user_attrs["resolved_params_literal"])
        refit_started = time.perf_counter()
        with _isolated_seed(seed_bank[0], evaluator.device):
            winner = evaluator.build(best_params, seed_bank[0])
            data.fit(_workflow(winner), refit=True)
            _synchronize(_workflow(winner))
        refit_seconds = time.perf_counter() - refit_started
        report = TuningReport(
            study,
            best_params,
            best.number,
            cast(float, best.value),
            best.user_attrs["nrmse"],
            seed_bank,
            seed_bank[0],
            data.report,
            fingerprint,
            attempts,
            time.perf_counter() - started,
            refit_seconds,
            tuple(best.user_attrs["runs"]),
            template,
            _model_hash(winner),
            resource_report,
        )
        _close_storage(owned, keep_study_usable=True)
        _install(model, winner, report)
        owned = None
        return model
    except BaseException as error:
        primary_error = error
        raise
    finally:
        _close_storage(owned, primary_error=primary_error, keep_study_usable=primary_error is None)

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 optuna.pruners.BasePruner.

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

model_creator(**resolved_settings) -> ESNModel. Fixed settings as well as suggested parameters are recorded. Capture custom Python modules/initializers in this callable rather than in JSON settings.

TYPE: callable

search_space

search_space(trial) -> mapping of finite JSON/literal settings.

TYPE: callable

data_loader

Returns 3D tensors keyed warmup, train, target, f_warmup and val. Each driver requires warmup/train/f_warmup/forecast entries with its name suffix. This function may also make Optuna suggestions.

TYPE: callable

n_trials

Positive count of NEW attempted configurations; transferred scores do not consume this budget. Resume adds this many attempts.

TYPE: int

loss

Raw forecast objective. Built-in/default losses minimize.

TYPE: str or callable DEFAULT: 'efh'

loss_params

Keyword options forwarded to the raw forecast objective.

TYPE: dict or None DEFAULT: None

targets_key

Name of the target readout.

TYPE: str DEFAULT: 'output'

drivers_keys

Declared driver data suffixes.

TYPE: list of str or None DEFAULT: None

monitor_losses

Additional final-horizon losses, recorded without changing the objective.

TYPE: (list, dict) DEFAULT: None

monitor_params

Additional final-horizon losses, recorded without changing the objective.

TYPE: (list, dict) DEFAULT: None

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: str DEFAULT: None

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: str DEFAULT: None

warm_start

Enqueue fixed settings for evaluation, preserving unsuggested values.

TYPE: list[dict] DEFAULT: None

transfer_from

Prior study or a path containing exactly one study. Full configurations are re-evaluated by default; source provenance is recorded.

TYPE: Study or str DEFAULT: None

sampler

Parent-owned sampling/pruning. Pruning at streamed horizon checkpoints stops future forecast generation; raw prefix scoring can retain history.

TYPE: Optuna objects or registered pruner name DEFAULT: None

pruner

Parent-owned sampling/pruning. Pruning at streamed horizon checkpoints stops future forecast generation; raw prefix scoring can retain history.

TYPE: Optuna objects or registered pruner name DEFAULT: None

seed

Trial initialization seed is seed + trial.number. Caller RNG streams are restored; the post-data-loading RNG sequence reaches the worker.

TYPE: int DEFAULT: None

device

Numerical model/data device. Parameter/scoring operations stay there when supported, with the existing NumPy custom-loss fallback.

TYPE: str or device DEFAULT: None

n_workers

Positive joblib worker count; one runs in the caller.

TYPE: int DEFAULT: 1

verbosity

Zero is quiet. Caller logging levels are restored after this call.

TYPE: int DEFAULT: 1

catch_exceptions

Record invalid evaluation attempts rather than aborting on their error.

TYPE: bool DEFAULT: True

penalty_value

Explicit numeric failure penalty when error_policy="penalty". error_policy="fail" prevents invalid evaluations becoming winners.

TYPE: float DEFAULT: 10000000000.0

clip_value

Optional upper bound on a completed trial loss.

TYPE: float or None DEFAULT: None

prune_on_clip

Prune a trial when its loss reaches clip_value.

TYPE: bool DEFAULT: False

horizon_key

Data key specifying the forecast length; cannot exceed validation truth.

TYPE: str DEFAULT: None

n_checkpoints

Growing forecast prefixes; reports use 1-based checkpoint indices.

TYPE: int DEFAULT: 5

torch_scoring

Prefer on-device numeric scoring until the final scalar.

TYPE: bool DEFAULT: True

trial_callbacks

Parent callbacks receive the real Trial and params/raw_loss/loss. TrialPruned propagates; other callback errors are logged/ignored.

TYPE: list[callable] DEFAULT: None

error_policy

Invalid evaluation representation. Penalty results are never valid winners.

TYPE: ('fail', 'penalty') DEFAULT: "fail"

transfer_mode

Copy evaluated scores only for identical bound task/objective protocols.

TYPE: ('reevaluate', 'scores') DEFAULT: "reevaluate"

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: mapping or str DEFAULT: None

inner_max_num_threads

joblib worker thread limit; caller thread settings remain unchanged.

TYPE: int DEFAULT: 1

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: optional DEFAULT: None

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: optional DEFAULT: None

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
def run_hpo(
    model_creator: Callable[..., ESNModel],
    search_space: Callable[[optuna.Trial], dict[str, Any]],
    data_loader: Callable[[optuna.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: optuna.Study | str | None = None,
    sampler: optuna.samplers.BaseSampler | None = None,
    pruner: str | optuna.pruners.BasePruner | None = None,
    seed: int | None = None,
    device: str | torch.device | None = None,
    n_workers: int = 1,
    verbosity: int = 1,
    catch_exceptions: bool = True,
    penalty_value: float = 1e10,
    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,
) -> optuna.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.

    Parameters
    ----------
    model_creator : callable
        `model_creator(**resolved_settings) -> ESNModel`. Fixed settings as
        well as suggested parameters are recorded. Capture custom Python
        modules/initializers in this callable rather than in JSON settings.
    search_space : callable
        `search_space(trial) -> mapping` of finite JSON/literal settings.
    data_loader : callable
        Returns 3D tensors keyed `warmup`, `train`, `target`, `f_warmup`
        and `val`. Each driver requires warmup/train/f_warmup/forecast entries
        with its name suffix. This function may also make Optuna suggestions.
    n_trials : int
        Positive count of NEW attempted configurations; transferred scores do
        not consume this budget. Resume adds this many attempts.
    loss : str or callable, optional
        Raw forecast objective. Built-in/default losses minimize.
    loss_params : dict or None, optional
        Keyword options forwarded to the raw forecast objective.
    targets_key : str, optional
        Name of the target readout.
    drivers_keys : list of str or None, optional
        Declared driver data suffixes.
    monitor_losses, monitor_params : list, dict, optional
        Additional final-horizon losses, recorded without changing the objective.
    study_name, storage : str, optional
        In-memory by default, or an explicit journal/SQLite study. Only the
        parent opens storage, so in-memory studies work with multiple workers.
    warm_start : list[dict], optional
        Enqueue fixed settings for evaluation, preserving unsuggested values.
    transfer_from : optuna.Study or str, optional
        Prior study or a path containing exactly one study. Full configurations
        are re-evaluated by default; source provenance is recorded.
    sampler, pruner : Optuna objects or registered pruner name, optional
        Parent-owned sampling/pruning. Pruning at streamed horizon checkpoints
        stops future forecast generation; raw prefix scoring can retain history.
    seed : int, optional
        Trial initialization seed is seed + trial.number. Caller RNG streams
        are restored; the post-data-loading RNG sequence reaches the worker.
    device : str or torch.device, optional
        Numerical model/data device. Parameter/scoring operations stay there
        when supported, with the existing NumPy custom-loss fallback.
    n_workers : int, default=1
        Positive joblib worker count; one runs in the caller.
    verbosity : int, default=1
        Zero is quiet. Caller logging levels are restored after this call.
    catch_exceptions : bool, default=True
        Record invalid evaluation attempts rather than aborting on their error.
    penalty_value : float, optional
        Explicit numeric failure penalty when `error_policy="penalty"`.
        `error_policy="fail"` prevents invalid evaluations becoming winners.
    clip_value : float or None, optional
        Optional upper bound on a completed trial loss.
    prune_on_clip : bool, optional
        Prune a trial when its loss reaches `clip_value`.
    horizon_key : str, optional
        Data key specifying the forecast length; cannot exceed validation truth.
    n_checkpoints : int, default=5
        Growing forecast prefixes; reports use 1-based checkpoint indices.
    torch_scoring : bool, default=True
        Prefer on-device numeric scoring until the final scalar.
    trial_callbacks : list[callable], optional
        Parent callbacks receive the real Trial and params/raw_loss/loss.
        TrialPruned propagates; other callback errors are logged/ignored.
    error_policy : {"fail", "penalty"}, default="fail"
        Invalid evaluation representation. Penalty results are never valid winners.
    transfer_mode : {"reevaluate", "scores"}, default="reevaluate"
        Copy evaluated scores only for identical bound task/objective protocols.
    task_context : mapping or str, optional
        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.
    inner_max_num_threads : int, default=1
        joblib worker thread limit; caller thread settings remain unchanged.
    memory_budget, memory_estimator : optional
        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.
    """
    if isinstance(n_trials, bool) or not isinstance(n_trials, int) or n_trials < 1:
        raise ValueError("n_trials must be a positive integer")
    if isinstance(n_workers, bool) or not isinstance(n_workers, int) or n_workers < 1:
        raise ValueError("n_workers must be positive")
    if (
        isinstance(inner_max_num_threads, bool)
        or not isinstance(inner_max_num_threads, int)
        or inner_max_num_threads < 1
    ):
        raise ValueError("inner_max_num_threads must be a positive integer")
    for callback, name in (
        (model_creator, "model_creator"),
        (search_space, "search_space"),
        (data_loader, "data_loader"),
    ):
        if not callable(callback):
            raise TypeError(f"{name} must be callable")
    if error_policy not in ("fail", "penalty"):
        raise ValueError("error_policy must be 'fail' or 'penalty'")
    if transfer_mode not in ("reevaluate", "scores"):
        raise ValueError("transfer_mode must be 'reevaluate' or 'scores'")
    if not math.isfinite(penalty_value):
        raise ValueError("penalty_value must be finite")
    budget = (
        memory_budget
        if isinstance(memory_budget, MemoryBudget) or memory_budget is None
        else MemoryBudget(memory_budget)
    )
    if budget is not None and memory_estimator is None:
        raise ValueError("Raw model factories require memory_estimator with memory_budget")
    if memory_estimator is not None and (budget is None or not callable(memory_estimator)):
        raise ValueError("memory_estimator must be callable and requires memory_budget")
    resolved_device = None if device is None else torch.device(device)
    levels = logging.getLogger("resdag").level, optuna.logging.get_verbosity()
    _configure_logging(verbosity)
    resolved_storage = None
    primary_error: BaseException | None = None
    try:
        # No worker connects to storage: a memory study is safe even in parallel.
        resolved_storage, _ = resolve_storage(storage, n_workers=1, return_path=True)
        base_loss = get_loss(loss)
        resolved_loss = partial(base_loss, **loss_params) if loss_params else base_loss
        monitors = [
            get_loss(item) if isinstance(item, str) else item for item in monitor_losses or ()
        ]
        mapped_monitor_params = dict(monitor_params or {})
        for original, resolved in zip(monitor_losses or (), monitors, strict=True):
            if isinstance(original, str) and original in mapped_monitor_params:
                mapped_monitor_params[getattr(resolved, "__name__", original)] = (
                    mapped_monitor_params.pop(original)
                )
        runner = build_objective(
            model_creator=model_creator,
            search_space=search_space,
            data_loader=data_loader,
            loss_fn=resolved_loss,
            targets_key=targets_key,
            drivers_keys=drivers_keys,
            horizon_key=horizon_key,
            catch_exceptions=catch_exceptions,
            penalty_value=penalty_value,
            monitor_losses=monitors,
            monitor_params=mapped_monitor_params,
            device=resolved_device,
            seed=seed,
            clip_value=clip_value,
            prune_on_clip=prune_on_clip,
            n_checkpoints=n_checkpoints,
            torch_scoring=torch_scoring,
            trial_callbacks=trial_callbacks,
            error_policy=error_policy,
        )
        payload = {
            "version": 2,
            "kind": "raw",
            "model": callable_identity(model_creator),
            "space": callable_identity(search_space),
            "data": callable_identity(data_loader),
            "loss": callable_identity(resolved_loss),
            "targets_key": targets_key,
            "drivers_keys": drivers_keys,
            "horizon_key": horizon_key,
            "seed": seed,
            "clip_value": clip_value,
            "prune_on_clip": prune_on_clip,
            "n_checkpoints": n_checkpoints,
            "torch_scoring": torch_scoring,
            "task_context": task_context,
            "error_policy": error_policy,
            "device": resolved_device,
            "environment": (platform.python_version(), torch.__version__, optuna.__version__),
        }
        protocol = fingerprint(payload)
        study = optuna.create_study(
            direction="minimize",
            study_name=study_name or make_study_name(model_creator),
            storage=resolved_storage,
            load_if_exists=True,
            sampler=sampler
            or TPESampler(multivariate=True, warn_independent_sampling=False, seed=seed),
            pruner=resolve_pruner(pruner),
        )
        bind_protocol(study, protocol)
        _validate_previous_data(study, runner, task_context)
        if transfer_from is not None:
            if transfer_mode == "scores":
                with _source_study(transfer_from) as source:
                    if source.user_attrs.get(PROTOCOL_KEY) != protocol:
                        raise ValueError(
                            "Score transfer requires identical task protocols; re-evaluate settings"
                        )
                    _validate_previous_data(source, runner, task_context)
                    transfer_trials(study, source, mode="scores", protocol_hash=protocol)
            else:
                transfer_trials(study, transfer_from)
        if warm_start:
            apply_warm_start(study, warm_start)
        run_trials(
            study,
            runner,
            n_trials=n_trials,
            n_workers=n_workers,
            verbosity=verbosity,
            inner_max_num_threads=inner_max_num_threads,
            memory_budget=budget,
            memory_estimator=memory_estimator,
        )
        completed = study.get_trials(states=(optuna.trial.TrialState.COMPLETE,))
        valid = [
            trial
            for trial in completed
            if "error" not in trial.user_attrs
            and not trial.user_attrs.get("nonfinite_loss", False)
            and trial.value is not None
            and math.isfinite(trial.value)
        ]
        failed = study.get_trials(states=(optuna.trial.TrialState.FAIL,))
        if not valid and (completed or failed):
            detail = (failed or completed)[0].user_attrs.get(
                "error", "Invalid/non-finite evaluation"
            )
            raise RuntimeError(f"No valid HPO trials completed. First evaluation error: {detail}")
        if valid and study.best_trial not in valid:
            raise RuntimeError(
                "The best score belongs to an invalid penalty evaluation; use error_policy='fail'"
            )
        return study
    except BaseException as error:
        primary_error = error
        raise
    finally:
        try:
            _close_storage(
                resolved_storage,
                primary_error=primary_error,
                keep_study_usable=primary_error is None,
            )
        finally:
            logging.getLogger("resdag").setLevel(levels[0])
            optuna.logging.set_verbosity(levels[1])

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
def transfer_trials(
    study: optuna.Study,
    transfer_from: "optuna.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.
    """
    if mode not in ("reevaluate", "scores"):
        raise ValueError("mode must be 'reevaluate' or 'scores'")
    with _source_study(transfer_from) as source:
        _require_distinct_studies(study, source)
        source_protocol = source.user_attrs.get(PROTOCOL_KEY)
        if mode == "scores":
            if (
                not protocol_hash
                or source_protocol != protocol_hash
                or study.user_attrs.get(PROTOCOL_KEY) != protocol_hash
            ):
                raise ValueError(
                    "Copying evaluated scores requires an identical bound task protocol; "
                    "use mode='reevaluate' to reuse settings for a new task"
                )
            if study.directions != source.directions:
                raise ValueError("Identical-score transfer requires matching objective directions")
        transferred = 0
        source_trials = source.get_trials(states=(TrialState.COMPLETE,))
        if mode == "reevaluate" and len(source.directions) == 1:
            maximize = source.direction == optuna.study.StudyDirection.MAXIMIZE
            source_trials.sort(
                key=lambda trial: (
                    (
                        (-(trial.value or 0.0) if maximize else trial.value or 0.0)
                        if trial.value is not None and isfinite(trial.value)
                        else float("inf")
                    ),
                    trial.number,
                )
            )
        entries = []
        for src in source_trials:
            values = src.values
            if (
                not values
                or not all(isfinite(value) for value in values)
                or "error" in src.user_attrs
                or src.user_attrs.get("nonfinite_loss", False)
            ):
                continue
            settings = trial_settings(src)
            if not settings:
                continue
            entries.append((src, settings))
        # Validate recorded configurations before changing the destination.
        # Storage write failures can still interrupt a standard Optuna import.
        for src, settings in entries:
            values = src.values
            provenance = {
                "mode": mode,
                "study_name": source.study_name,
                "trial_number": src.number,
                "protocol_hash": source_protocol,
                "resolved_settings_literal": repr(settings),
            }
            if mode == "reevaluate":
                study.enqueue_trial(
                    {**src.params, **settings},
                    user_attrs={"resdag_transfer": provenance, REUSED_SETTINGS_KEY: repr(settings)},
                    skip_if_exists=False,
                )
            else:
                attrs = dict(src.user_attrs)
                attrs["resdag_transfer"] = provenance
                attrs[RESOLVED_SETTINGS_KEY] = repr(settings)
                study.add_trial(
                    optuna.trial.create_trial(
                        state=TrialState.COMPLETE,
                        values=values,
                        params=dict(src.params),
                        distributions=dict(src.distributions),
                        user_attrs=attrs,
                    )
                )
            transferred += 1
        return transferred

apply_warm_start

apply_warm_start(study: Study, warm_start: list[dict[str, Any]]) -> int

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: Study

warm_start

Each dict maps parameter name to a fixed value. Empty or None entries are ignored.

TYPE: list of dict

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
def apply_warm_start(
    study: optuna.Study,
    warm_start: list[dict[str, Any]],
) -> int:
    """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.

    Parameters
    ----------
    study : optuna.Study
        The study to enqueue trials into.
    warm_start : list of dict
        Each dict maps parameter name to a fixed value.  Empty or `None`
        entries are ignored.

    Returns
    -------
    int
        The number of configurations enqueued.

    Examples
    --------
    >>> apply_warm_start(study, [{"reservoir_size": 300, "spectral_radius": 0.9}])
    1
    """
    if not warm_start:
        return 0

    count = 0
    for params in warm_start:
        if not params:
            continue
        settings = resolved_settings(params)
        study.enqueue_trial(
            settings, user_attrs={REUSED_SETTINGS_KEY: repr(settings)}, skip_if_exists=False
        )
        count += 1

    if count:
        logger.info("Warm-started study with %d enqueued trial(s)", count)
    return count

export_best_config

export_best_config(study: Study) -> dict[str, Any]

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 COMPLETE trial.

TYPE: Study

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
def export_best_config(study: optuna.Study) -> dict[str, Any]:
    """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.

    Parameters
    ----------
    study : optuna.Study
        A study with at least one `COMPLETE` trial.

    Returns
    -------
    dict
        Complete recorded resolved settings, including fixed factory values.
        External studies without that record fall back to their suggestions.

    Raises
    ------
    ValueError
        If the study has no completed trials.

    Examples
    --------
    >>> best = export_best_config(study)
    >>> run_hpo(..., warm_start=[best])  # doctest: +SKIP
    """
    completed = [t for t in study.trials if t.state == TrialState.COMPLETE]
    if not completed:
        raise ValueError("Cannot export best config: study has no completed trials.")
    best = study.best_trial
    if (
        "error" in best.user_attrs
        or best.user_attrs.get("nonfinite_loss", False)
        or best.value is None
        or not isfinite(best.value)
    ):
        raise ValueError("Cannot export an invalid or non-finite winning configuration")
    return {**best.params, **trial_settings(best)}

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

validate(full_seed_count: int, full_origin_count: int) -> None

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
def validate(self, full_seed_count: int, full_origin_count: int) -> None:
    """Reject a screen that asks for more repetitions than full evaluation."""
    seeds = _integer(full_seed_count, "full_seed_count", minimum=1)
    origins = _integer(full_origin_count, "full_origin_count", minimum=1)
    if self.seed_count > seeds or self.origin_count > origins:
        raise ValueError("Screening seed/origin counts cannot exceed full evaluation counts")

promoted_count

promoted_count(n: int) -> int

Round promotion upward; a nonempty cohort always retains a candidate.

Source code in src/resdag/hpo/resources.py
125
126
127
128
129
def promoted_count(self, n: int) -> int:
    """Round promotion upward; a nonempty cohort always retains a candidate."""
    n = _integer(n, "cohort size")
    numerator, denominator = Decimal(str(self.keep_fraction)).as_integer_ratio()
    return min(n, (n * numerator + denominator - 1) // denominator)

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.

limit_bytes property

limit_bytes: int

The parsed combined limit as integer bytes.

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
def fits(self, 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.
    """
    estimates = (*current, estimate)
    if any(not isinstance(item, MemoryEstimate) for item in estimates):
        raise TypeError("fits expects MemoryEstimate instances")
    host = sum(item.host_bytes for item in estimates)
    device = sum(item.device_bytes for item in estimates)
    total = host + device + len(estimates) * cast(int, self.worker_overhead)
    return total <= cast(int, self.limit) and (
        self.device_limit is None or device <= cast(int, self.device_limit)
    )

MemoryEstimate dataclass

MemoryEstimate(
    host_bytes: int, device_bytes: int = 0, details: Mapping[str, Any] = dict()
)

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.

total_bytes property

total_bytes: int

Host plus device planning bytes, before per-worker overhead.

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.

batch_size property

batch_size: int

Number of independent input sequences; unbatched data counts as one.

input_features property

input_features: int

Sum of signal widths across the model's input ports.

output_features property

output_features: int

Sum of supervised target widths across output ports.

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
def 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.
    """
    if not isinstance(params, Mapping) or not isinstance(context, MemoryContext):
        raise TypeError("estimate_memory expects parameter mapping and MemoryContext")
    if estimator is not None:
        if not callable(estimator):
            raise TypeError("memory estimator must be callable")
        result = estimator(copy.deepcopy(dict(params)), context)
        if not isinstance(result, MemoryEstimate):
            result = MemoryEstimate(_integer(result, "custom memory estimate"))
        host = context.dataset_host_bytes + context.model_host_bytes
        device = context.dataset_device_bytes + context.model_device_bytes
        retained = context.retained_forecast_bytes + context.replay_history_bytes
        if context.device.type == "cpu":
            host += retained
        else:
            device += retained
        return MemoryEstimate(
            max(result.host_bytes, host),
            max(result.device_bytes, device),
            {
                **result.details,
                "requested_host_bytes": result.host_bytes,
                "requested_device_bytes": result.device_bytes,
                "minimum_host_bytes": host,
                "minimum_device_bytes": device,
                "retained_forecast_bytes": context.retained_forecast_bytes,
                "replay_history_bytes": context.replay_history_bytes,
                "floor_applied": result.host_bytes < host or result.device_bytes < device,
            },
        )
    if custom_factory:
        raise ValueError(
            "A custom factory with a memory budget requires memory_estimator(params, context)"
        )
    if not context.readout_features:
        raise ValueError("Unknown readout widths require a custom memory estimator")
    element = torch.finfo(context.dtype).bits // 8
    n = max(context.train_samples, context.refit_samples)
    features, outputs = context.readout_features, context.readout_outputs
    model = context.model_host_bytes + context.model_device_bytes
    activation_width = context.activation_width
    if context.preset_options:
        options = {**context.preset_options, **params}
        width = _integer(options.get("reservoir_size", 500), "reservoir_size", minimum=1)
        inputs, output = context.input_features, context.output_features
        skip = options.get("input_to_readout", True)
        if not isinstance(skip, bool):
            raise ValueError("input_to_readout must be a bool")
        feedback = _integer(options.get("feedback_size", inputs), "feedback_size", minimum=1)
        features, outputs = (width + (feedback if skip else 0),), (output,)
        # Dense recurrence, feedback/input projection, vector bias/leak/state
        # and readout; no reservoir, initializer or layer is constructed here.
        model = max(
            model, element * (width * width + width * (inputs + 3) + output * (features[0] + 1))
        )
        activation_width = width * 3 + inputs + output + (feedback if skip else 0)
    resident_host = context.dataset_host_bytes + 3 * context.model_host_bytes
    resident_device = context.dataset_device_bytes + 3 * context.model_device_bytes
    model_copies = 3 * model
    fit_data = 4 * n * (context.input_features + context.output_features) * element
    trace_samples = max(n, context.forecast_samples)
    traces = 4 * trace_samples * activation_width * element
    parallel_components: dict[str, int] = {}
    if context.sequence_layout.get("kind") == "parallel":
        layout = context.sequence_layout
        patches = _integer(layout["patches"], "patches", minimum=1)
        rows = trace_samples * patches
        # Input and target window gathers, projected inputs, retained features
        # and core targets all have patch-batched time axes. Retain the same
        # conservative four-copy allowance as the general trace estimate.
        for name, width_name in (
            ("input_windows", "patch_width"),
            ("target_windows", "patch_width"),
            ("projected_inputs", "projection_width"),
            ("features", "feature_width"),
            ("core_targets", "output_width"),
        ):
            parallel_components[name] = (
                4 * rows * _integer(layout[width_name], width_name, minimum=1) * element
            )
        parallel_components["recurrent_state"] = (
            4
            * context.batch_size
            * patches
            * _integer(layout["state_width"], "state_width", minimum=1)
            * element
        )
        traces = max(traces, sum(parallel_components.values()))
    forecasts = 3 * max(
        context.retained_forecast_bytes,
        context.batch_size * context.output_features * element,
    )
    # QR augmentation and compact SVD, plus centered/cast inputs, inverse-norm
    # guards and factorization work arrays. Sum heads to cover retained features.
    readout_samples = tuple(
        max(
            n,
            context.readout_train_samples[index] if context.readout_train_samples else n,
            context.readout_refit_samples[index] if context.readout_refit_samples else n,
        )
        for index in range(len(features))
    )
    if context.sequence_layout.get("kind") == "parallel":
        layout = context.sequence_layout
        washout = _integer(params.get("washout", layout["washout"]), "washout")
        pooled = max(
            layout[phase]["window"][0]
            * max(
                0,
                layout[phase]["supervised_stop"] - max(washout, layout[phase]["supervised_start"]),
            )
            for phase in ("train", "refit")
        )
        readout_samples = (max(*readout_samples, pooled),)
    workspace = sum(
        8 * (6 * rows * (f + out) + 12 * f * f + 6 * min(rows, f) ** 2 + 4 * f * out)
        for rows, f, out in zip(readout_samples, features, outputs)
    )
    working = (
        model_copies + fit_data + traces + forecasts + context.replay_history_bytes + workspace
    )
    host, device = resident_host, resident_device
    bridge = 0
    if context.device.type == "cpu":
        host += working
    else:
        device += working
        bridge = workspace
        host += bridge
    return MemoryEstimate(
        host,
        device,
        {
            "kind": "planning estimate; not a hard cap",
            "samples": n,
            "element_bytes": element,
            "model_copies": model_copies,
            "fit_data": fit_data,
            "feature_traces": traces,
            "trace_samples": trace_samples,
            "readout_samples": readout_samples,
            "readout_features": features,
            "parallel_trace_components": parallel_components,
            "forecast_outputs": forecasts,
            "replay_history": context.replay_history_bytes,
            "solve_workspace": workspace,
            "cpu_bridge": bridge,
        },
    )

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.

TYPE: str or callable

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
def get_loss(key_or_callable: str | LossProtocol) -> LossProtocol:
    """Get a loss function by key or return the callable directly.

    Parameters
    ----------
    key_or_callable : str or callable
        Either a string key from LOSSES (e.g., "efh") or a custom callable
        following the LossProtocol interface.

    Returns
    -------
    LossProtocol
        The loss function callable.

    Raises
    ------
    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)
    """
    if isinstance(key_or_callable, str):
        if key_or_callable not in LOSSES:
            available = ", ".join(LOSSES.keys())
            raise KeyError(f"Unknown loss '{key_or_callable}'. Available: {available}")
        return cast(LossProtocol, LOSSES[key_or_callable])

    if not callable(key_or_callable):
        raise TypeError("Loss must be a string key or a callable.")

    return key_or_callable

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: ndarray

y_pred

Predicted values of shape (B, T, D).

TYPE: ndarray

metric

Error metric: "rmse", "mse", "mae", or "nrmse".

TYPE: str DEFAULT: 'nrmse'

threshold

Error threshold below which predictions are considered "good".

TYPE: float DEFAULT: 0.2

softness

Controls the width of the soft threshold boundary. Smaller values create a harder threshold. The default is 0.04.

TYPE: float DEFAULT: 0.04

RETURNS DESCRIPTION
float

Negative expected forecast horizon. Lower (more negative) is better.

WARNS DESCRIPTION
UserWarning

If metric is not scale-free (i.e. not "nrmse"), since the fixed threshold is then only meaningful on unit-scale data.

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
def expected_forecast_horizon(
    y_true: NDArray[np.floating],
    y_pred: NDArray[np.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.

    Parameters
    ----------
    y_true : ndarray
        True values of shape (B, T, D).
    y_pred : ndarray
        Predicted values of shape (B, T, D).
    metric : str, optional
        Error metric: `"rmse"`, `"mse"`, `"mae"`, or `"nrmse"`.
    threshold : float, default=0.2
        Error threshold below which predictions are considered "good".
    softness : float, optional
        Controls the width of the soft threshold boundary. Smaller values
        create a harder threshold. The default is `0.04`.

    Returns
    -------
    float
        Negative expected forecast horizon. Lower (more negative) is better.

    Warns
    -----
    UserWarning
        If *metric* is not scale-free (i.e. not `"nrmse"`), since the fixed
        *threshold* is then only meaningful on unit-scale data.
    """
    _warn_if_scale_unsafe(metric, "expected_forecast_horizon", threshold)
    errors = _compute_errors(y_true, y_pred, metric)  # (B, T)
    e_t = _aggregate_batch(errors, how="median")  # Robust across batch

    # Soft indicator of "good prediction" at each step
    good_t = expit((threshold - e_t) / softness)  # ∈ (0, 1)

    # Survival probability: product of all good indicators up to t
    # log_g = np.log(np.clip(good_t, 1e-12, 1.0))
    surv_t = np.cumprod(good_t)

    # Expected horizon length
    expected_horizon = np.sum(surv_t)

    return -float(expected_horizon)  # Minimize → maximize horizon

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: ndarray

y_pred

Predicted values of shape (B, T, D).

TYPE: ndarray

metric

Error metric: "rmse", "mse", "mae", or "nrmse". Defaults to the scale-free "nrmse" so the fixed threshold is comparable across datasets of any magnitude.

TYPE: str DEFAULT: 'nrmse'

threshold

Error threshold below which predictions are considered valid.

TYPE: float DEFAULT: 0.2

RETURNS DESCRIPTION
float

Negative of the valid horizon length. Lower is better.

WARNS DESCRIPTION
UserWarning

If metric is not scale-free (i.e. not "nrmse"), since the fixed threshold is then only meaningful on unit-scale data.

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
def forecast_horizon(
    y_true: NDArray[np.floating],
    y_pred: NDArray[np.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.

    Parameters
    ----------
    y_true : ndarray
        True values of shape (B, T, D).
    y_pred : ndarray
        Predicted values of shape (B, T, D).
    metric : str, optional
        Error metric: `"rmse"`, `"mse"`, `"mae"`, or `"nrmse"`.  Defaults to the scale-free `"nrmse"` so the
        fixed *threshold* is comparable across datasets of any magnitude.
    threshold : float, default=0.2
        Error threshold below which predictions are considered valid.

    Returns
    -------
    float
        Negative of the valid horizon length. Lower is better.

    Warns
    -----
    UserWarning
        If *metric* is not scale-free (i.e. not `"nrmse"`), since the fixed
        *threshold* is then only meaningful on unit-scale data.
    """
    _warn_if_scale_unsafe(metric, "forecast_horizon", threshold)
    errors = _compute_errors(y_true, y_pred, metric)  # (B, T)
    e_t = _aggregate_batch(errors, how="median")  # Robust across batch

    below = e_t < threshold
    if not below[0]:
        valid_len = 0
    else:
        valid_len = int(np.argmax(~below)) if (~below).any() else int(below.size)

    return -float(valid_len)

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: ndarray

y_pred

Predicted values of shape (B, T, D).

TYPE: ndarray

metric

Per-step error metric: "rmse", "mse", "mae", or "nrmse". Defaults to the scale-free "nrmse" so the magnitude is comparable across datasets.

TYPE: str DEFAULT: 'nrmse'

lyapunov_t

Characteristic Lyapunov time (in time steps) controlling the exponential decay rate of the weights.

TYPE: int DEFAULT: 64

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
def lyapunov_weighted(
    y_true: NDArray[np.floating],
    y_pred: NDArray[np.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).

    Parameters
    ----------
    y_true : ndarray
        True values of shape (B, T, D).
    y_pred : ndarray
        Predicted values of shape (B, T, D).
    metric : str, optional
        Per-step error metric: `"rmse"`, `"mse"`, `"mae"`, or `"nrmse"`.  Defaults to the scale-free
        `"nrmse"` so the magnitude is comparable across datasets.
    lyapunov_t : int, default=64
        Characteristic Lyapunov time (in time steps) controlling the
        exponential decay rate of the weights.

    Returns
    -------
    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`).
    """
    errors = _compute_errors(y_true, y_pred, metric)  # (B, T)
    e_t = _aggregate_batch(errors, how="gmean")  # (T,)

    t = np.arange(e_t.shape[0])
    weights = np.exp(-t / lyapunov_t)

    return float(np.sum(weights * e_t) / np.sum(weights))

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: ndarray

y_pred

Predicted values of shape (B, T, D).

TYPE: ndarray

metric

Error metric: "rmse", "mse", "mae", or "nrmse".

TYPE: str DEFAULT: 'nrmse'

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
def standard_loss(
    y_true: NDArray[np.floating],
    y_pred: NDArray[np.floating],
    /,
    metric: MetricType = "nrmse",
) -> float:
    """Mean geometric mean error across all timesteps.

    Simple baseline loss suitable for both stable and unstable systems.

    Parameters
    ----------
    y_true : ndarray
        True values of shape (B, T, D).
    y_pred : ndarray
        Predicted values of shape (B, T, D).
    metric : str, optional
        Error metric: `"rmse"`, `"mse"`, `"mae"`, or `"nrmse"`.

    Returns
    -------
    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`.
    """
    errors = _compute_errors(y_true, y_pred, metric)
    geom_mean = _aggregate_batch(errors, how="gmean")
    return float(np.mean(geom_mean))

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:

\[ g_t = \frac{1}{1 + (e_t / \theta)^n} \]

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:

\[ H = \sum_t \prod_{i \leq t} g_i \]

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: ndarray

y_pred

Predicted values of shape (B, T, D).

TYPE: ndarray

metric

Per-step error metric: "rmse", "mse", "mae", or "nrmse". Defaults to the scale-free "nrmse" so the fixed threshold is comparable across datasets.

TYPE: str DEFAULT: 'nrmse'

threshold

Error threshold below which predictions are considered "good".

TYPE: float DEFAULT: 0.3

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: int DEFAULT: 6

RETURNS DESCRIPTION
float

Negative expected horizon. Lower (more negative) is better.

WARNS DESCRIPTION
UserWarning

If metric is not scale-free (i.e. not "nrmse"), since the fixed threshold is then only meaningful on unit-scale data.

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
def soft_valid_horizon(
    y_true: NDArray[np.floating],
    y_pred: NDArray[np.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:

    $$
    g_t = \\frac{1}{1 + (e_t / \\theta)^n}
    $$

    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:

    $$
    H = \\sum_t \\prod_{i \\leq t} g_i
    $$

    The function is numerically safe: error ratios are clipped before
    exponentiation to prevent overflow.

    Parameters
    ----------
    y_true : ndarray
        True values of shape (B, T, D).
    y_pred : ndarray
        Predicted values of shape (B, T, D).
    metric : str, optional
        Per-step error metric: `"rmse"`, `"mse"`, `"mae"`, or `"nrmse"`.  Defaults to the scale-free
        `"nrmse"` so the fixed *threshold* is comparable across datasets.
    threshold : float, default=0.3
        Error threshold below which predictions are considered "good".
    n : int, default=6
        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.

    Returns
    -------
    float
        Negative expected horizon.  Lower (more negative) is better.

    Warns
    -----
    UserWarning
        If *metric* is not scale-free (i.e. not `"nrmse"`), since the fixed
        *threshold* is then only meaningful on unit-scale data.

    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.
    """
    _warn_if_scale_unsafe(metric, "soft_valid_horizon", threshold)
    errors = _compute_errors(y_true, y_pred, metric)  # (B, T)
    e_t = _aggregate_batch(errors, how="median")  # (T,) — robust across batch

    # Numerically safe Hill gate: clip the ratio to avoid overflow in x**n
    ratio = np.clip(e_t / threshold, 0.0, 1e4)
    good_t = 1.0 / (1.0 + ratio**n)

    # Survival (cumulative product) — once one step fails, all later are ~0
    surv_t = np.cumprod(good_t)

    horizon = np.sum(surv_t)
    return -float(horizon)

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:

\[ \mathcal{L} = \big|\, D_2(\hat y) - D_2(y) \,\big|. \]

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 (B, T, D). Its per-batch-element trajectories are concatenated along time into one (B*T, D) point cloud before the dimension estimate (a single attractor sampled by all batch elements).

TYPE: ndarray

y_pred

Forecast trajectory of shape (B, T, D) (same convention).

TYPE: ndarray

max_points

Cap on the points used per dimension estimate (the pair count is \(O(M^2)\)); longer trajectories are subsampled.

TYPE: int DEFAULT: 2000

n_bins

Number of log-spaced radii in the correlation sum.

TYPE: int DEFAULT: 20

fit_window

Scaling region (as fractions of the log-radius span) over which the \(\log C\) vs \(\log r\) slope is fit.

TYPE: tuple of float DEFAULT: (0.1, 0.5)

seed

Seed for the subsampling draw, so the loss is deterministic.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
float

\(|D_2(\hat y) - D_2(y)|\ge 0\). Lower is better; 0 means the forecast's attractor has the true correlation dimension.

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
def attractor_dimension_error(
    y_true: NDArray[np.floating],
    y_pred: NDArray[np.floating],
    /,
    max_points: int = 2000,
    n_bins: int = 20,
    fit_window: tuple[float, float] = (0.1, 0.5),
    seed: int = 0,
) -> float:
    r"""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:

    $$
    \mathcal{L} = \big|\, D_2(\hat y) - D_2(y) \,\big|.
    $$

    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).

    Parameters
    ----------
    y_true : ndarray
        Ground-truth trajectory of shape `(B, T, D)`.  Its per-batch-element
        trajectories are concatenated along time into one `(B*T, D)` point
        cloud before the dimension estimate (a single attractor sampled by all
        batch elements).
    y_pred : ndarray
        Forecast trajectory of shape `(B, T, D)` (same convention).
    max_points : int, default=2000
        Cap on the points used per dimension estimate (the pair count is
        $O(M^2)$); longer trajectories are subsampled.
    n_bins : int, default=20
        Number of log-spaced radii in the correlation sum.
    fit_window : tuple of float, default=(0.1, 0.5)
        Scaling region (as fractions of the log-radius span) over which the
        $\log C$ vs $\log r$ slope is fit.
    seed : int, default=0
        Seed for the subsampling draw, so the loss is deterministic.

    Returns
    -------
    float
        $|D_2(\hat y) - D_2(y)|\ge 0$.  Lower is better; `0` means the
        forecast's attractor has the true correlation dimension.

    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.
    """
    # Imported lazily so importing the (optional-HPO) losses module never pulls
    # in the metrics observables at module load.
    from resdag.metrics import correlation_dimension

    if y_true.shape != y_pred.shape:
        raise ValueError(f"Shape mismatch: {y_true.shape} vs {y_pred.shape}")

    def _flatten(arr: NDArray[np.floating]) -> NDArray[np.floating]:
        a = np.asarray(arr, dtype=np.float64)
        if a.ndim == 3:
            a = a.reshape(-1, a.shape[-1])  # (B*T, D)
        return a

    d2_true = correlation_dimension(
        _flatten(y_true), n_bins=n_bins, fit_window=fit_window, max_points=max_points, seed=seed
    )
    d2_pred = correlation_dimension(
        _flatten(y_pred), n_bins=n_bins, fit_window=fit_window, max_points=max_points, seed=seed
    )
    return abs(float(d2_pred) - float(d2_true))

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

get_study_summary(study: Study, top_n: int = 5) -> str

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: Study

top_n

Number of top-performing trials to include.

TYPE: int DEFAULT: 5

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
def get_study_summary(study: optuna.Study, top_n: int = 5) -> str:
    """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.

    Parameters
    ----------
    study : optuna.Study
        The Optuna study to summarize.
    top_n : int, default=5
        Number of top-performing trials to include.

    Returns
    -------
    str
        Formatted multi-line summary string.

    Example
    -------
    >>> study = optuna.create_study()
    >>> # ... run optimization ...
    >>> print(get_study_summary(study))
    """
    lines = []
    lines.append("=" * 60)
    lines.append("Study Summary")
    lines.append("=" * 60)
    lines.append(f"Study Name: {study.study_name}")

    total_trials = len(study.trials)
    completed = len([t for t in study.trials if t.state == optuna.trial.TrialState.COMPLETE])
    pruned = len([t for t in study.trials if t.state == optuna.trial.TrialState.PRUNED])
    failed = len([t for t in study.trials if t.state == optuna.trial.TrialState.FAIL])

    lines.append(f"Total Trials: {total_trials}")
    lines.append(f"  Completed: {completed}")
    lines.append(f"  Pruned: {pruned}")
    lines.append(f"  Failed: {failed}")
    lines.append("")

    if completed > 0:
        lines.append("-" * 60)
        lines.append("Best Trial")
        lines.append("-" * 60)
        lines.append(f"Trial Number: {study.best_trial.number}")
        lines.append(f"Value: {study.best_value:.6f}")
        lines.append("")
        lines.append("Parameters:")
        for k, v in study.best_params.items():
            if isinstance(v, float):
                lines.append(f"  {k}: {v:.6f}")
            else:
                lines.append(f"  {k}: {v}")
        lines.append("")

        # COMPLETE single-objective trials have a value. Keep a defensive
        # missing-value fallback last in either objective direction.
        completed_trials = [t for t in study.trials if t.state == optuna.trial.TrialState.COMPLETE]
        maximizing = study.direction == optuna.study.StudyDirection.MAXIMIZE
        missing_value = float("-inf") if maximizing else float("inf")
        sorted_trials = sorted(
            completed_trials,
            key=lambda t: t.value if t.value is not None else missing_value,
            reverse=maximizing,
        )

        lines.append("-" * 60)
        lines.append(f"Top {min(top_n, len(sorted_trials))} Trials")
        lines.append("-" * 60)
        for i, trial in enumerate(sorted_trials[:top_n], 1):
            lines.append(f"{i}. Trial {trial.number}: {trial.value:.6f}")

    lines.append("=" * 60)
    return "\n".join(lines)

make_study_name

make_study_name(model_creator: Callable) -> str

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.partial objects are unwrapped to their underlying function so the wrapped factory's name and source file are used (a bare partial raises TypeError in inspect.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 their repr, 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 functools.partial, a lambda, or any callable object.

TYPE: Callable

RETURNS DESCRIPTION
str

Study name in the format "filename:identifier". filename is "<unknown>" when the source file cannot be determined.

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
def make_study_name(model_creator: Callable) -> str:
    """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.partial` objects are unwrapped to their underlying function so
      the wrapped factory's name and source file are used (a bare `partial`
      raises `TypeError` in `inspect.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 their
      `repr`, so two logically-distinct creators do not collide onto the same
      study name and silently share persisted storage.

    Parameters
    ----------
    model_creator : Callable
        The model creator callable to generate a name from. May be a plain
        function, a `functools.partial`, a lambda, or any callable object.

    Returns
    -------
    str
        Study name in the format `"filename:identifier"`. `filename` is
        `"<unknown>"` when the source file cannot be determined.

    Example
    -------
    >>> def my_model_creator(units):
    ...     return model
    >>> make_study_name(my_model_creator)
    'script:my_model_creator'
    """
    fn = _unwrap_callable(model_creator)

    try:
        src = inspect.getsourcefile(fn) or "<interactive>"
    except (TypeError, OSError):
        src = "<unknown>"

    name = getattr(fn, "__name__", None)
    if not name or name == "<lambda>":
        digest = hashlib.sha1(repr(model_creator).encode("utf-8")).hexdigest()[:8]
        name = f"{type(fn).__name__}-{digest}"

    return f"{Path(src).stem}:{name}"

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: Study

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
def get_best_params(study: optuna.Study) -> dict:
    """Get the best parameters from a study.

    Convenience function that returns the best trial's parameters.

    Parameters
    ----------
    study : optuna.Study
        The Optuna study.

    Returns
    -------
    dict
        Dictionary of best hyperparameters.

    Raises
    ------
    ValueError
        If no completed trials exist.
    """
    completed = [t for t in study.trials if t.state == optuna.trial.TrialState.COMPLETE]
    if not completed:
        raise ValueError("No completed trials in study.")
    return study.best_params