Skip to content

Reference

Models & ensembles

Architecture factories return ready-to-use reservoir models. headless_esn and linear_esn omit the readout; parallel_esn returns a ParallelESNModel for spatial patching, while coupled_ensemble_esn builds the CoupledEnsembleESNModel wrapper. The other factories return ESNModel instances with a configured readout. KnowledgeModel adapts a physics prior for hybrid_esn.

models

Premade ESN Architectures

This module provides pre-configured ESN model architectures that can be used directly or customized for specific tasks.

FUNCTION DESCRIPTION
classic_esn

Traditional ESN with input concatenation.

ott_esn

Ott's ESN with state augmentation (squared even units).

power_augmented

Power Augmented ESN with state augmentation (exponentiated reservoir states).

deep_esn

Deep (hierarchical) ESN — a stack of reservoir layers whose readout sees the concatenation of every layer's state.

hybrid_esn

Hybrid physics-prior ESN (Pathak et al. 2018) — a reservoir combined with a knowledge-based expert wired in before the reservoir and before the readout.

headless_esn

Reservoir only (no readout) for analysis.

linear_esn

Linear reservoir for baseline comparison.

lsm

Spiking Liquid State Machine — leaky integrate-and-fire reservoir with a filtered-spike-trace readout (input-driven; not a chaos forecaster).

parallel_esn

Parallel local-state reservoir (Pathak et al. 2018) — one shared reservoir advanced batched over overlapping spatial patches, for forecasting large spatiotemporally chaotic systems (PDEs / weather / lattices).

coupled_ensemble_esn

Build a resdag.ensemble.CoupledEnsembleESNModel of N coupled ESN sub-models sharing an averaged feedback signal.

CLASS DESCRIPTION
KnowledgeModel

torch.nn.Module adapter wrapping a knowledge-based expert f(u) -> u_next for use inside hybrid_esn.

ParallelESNModel

The model class parallel_esn builds — a shared reservoir plus a weight-tied readout with patch windowing / stitching and a spatial- autoregressive resdag.models.ParallelESNModel.forecast.

Each architecture accepts individual parameters for full customization
while providing sensible defaults for quick experimentation.

Examples:

Quick start with Ott's ESN:

>>> from resdag.models import ott_esn
>>> model = ott_esn(reservoir_size=500, feedback_size=3, output_size=3)
>>> predictions = model.forecast(warmup_data, horizon=100)

Classic ESN with custom topology:

>>> from resdag.models import classic_esn
>>> from resdag.init.topology import get_topology
>>>
>>> model = classic_esn(
...     reservoir_size=500,
...     feedback_size=3,
...     output_size=3,
...     topology=get_topology("watts_strogatz", k=4, p=0.3),
...     spectral_radius=0.95,
... )
See Also

resdag.core.ESNModel : Base ESN model class. resdag.layers.ESNLayer : ESN layer used by these models. resdag.training.ESNTrainer : Trainer for fitting readout layers.

classic_esn

classic_esn(
    reservoir_size: int,
    feedback_size: int,
    output_size: int,
    input_size: int | None = None,
    input_initializer: InitializerSpec | None = None,
    topology: TopologySpec | None = None,
    spectral_radius: float = 0.9,
    leak_rate: float = 1.0,
    noise: float = 0.0,
    feedback_initializer: InitializerSpec | None = None,
    activation: str = "tanh",
    bias: bool = True,
    trainable: bool = False,
    readout: ReadoutSpec = "ridge",
    readout_alpha: float = 1e-06,
    readout_bias: bool = True,
    readout_name: str = "output",
    readout_kwargs: dict[str, Any] | None = None,
    input_to_readout: bool = True,
    **reservoir_kwargs: Any
) -> ESNModel

Build a classic Echo State Network (ESN) model.

By default, this architecture concatenates the input with the reservoir output before passing to the readout layer. Set input_to_readout=False to fit the readout on reservoir states alone.

Architecture:

Input -> Reservoir -> Concatenate(Input, Reservoir) -> Readout

The readout sees both the raw input and the reservoir's nonlinear transformation, which can improve performance on many tasks.

PARAMETER DESCRIPTION
reservoir_size

Number of units in the reservoir.

TYPE: int

feedback_size

Number of feedback features (input dimension).

TYPE: int

output_size

Number of output features.

TYPE: int

input_size

Dimension of an optional driving (exogenous) input. When given, the model takes two inputs (feedback, driver) and the driver feeds the reservoir alongside the autoregressive feedback. The driver is kept out of the input concatenation, so the readout in_features is feedback_size + reservoir_size when input_to_readout=True and reservoir_size otherwise. None (default) builds a feedback-only model, unchanged from previous behavior.

TYPE: int or None DEFAULT: None

input_initializer

Initializer for the driving-input weights. Same accepted forms as feedback_initializer. Only used when input_size is given.

TYPE: InitializerSpec DEFAULT: None

topology

Topology for recurrent weights. Accepts:

  • str: Registry name (e.g., "erdos_renyi")
  • tuple: (name, params) like ("watts_strogatz", {"k": 6, "p": 0.1})
  • resdag.init.topology.TopologyInitializer: Pre-configured object

TYPE: TopologySpec DEFAULT: None

spectral_radius

Desired spectral radius for recurrent weights.

TYPE: float DEFAULT: 0.9

leak_rate

Leaky integration rate (1.0 = no leak).

TYPE: float DEFAULT: 1.0

noise

Standard deviation of additive Gaussian state noise injected into the reservoir after the activation. Active only in training mode (a no-op under torch.nn.Module.eval); 0.0 disables it. Forwarded to resdag.layers.ESNLayer. Must be non-negative.

TYPE: float DEFAULT: 0.0

feedback_initializer

Initializer for feedback weights. Accepts:

  • str: Registry name (e.g., "pseudo_diagonal")
  • tuple: (name, params) like ("chebyshev", {"p": 0.5})
  • resdag.init.input_feedback.InputFeedbackInitializer: Pre-configured object

TYPE: InitializerSpec DEFAULT: None

activation

Activation function ("tanh", "relu", "sigmoid", "identity").

TYPE: str DEFAULT: "tanh"

bias

Whether to use bias in the reservoir.

TYPE: bool DEFAULT: True

trainable

Whether reservoir weights are trainable.

TYPE: bool DEFAULT: False

readout

A built-in name ("ridge", "cholesky", "cg", "svd", "pinv", "incremental", "rls", "fista", "lsmr") or a resdag.layers.readouts.ReadoutLayer subclass. Additional solver options go in readout_kwargs.

TYPE: str or type[ReadoutLayer] DEFAULT: "ridge"

readout_alpha

Ridge regression regularization for readout.

TYPE: float DEFAULT: 1e-6

readout_bias

Whether to use bias in the readout.

TYPE: bool DEFAULT: True

input_to_readout

Whether to append the raw feedback input to the reservoir states seen by the readout. Exogenous driving inputs are never appended.

TYPE: bool DEFAULT: True

readout_name

Name for the readout layer (used in training targets).

TYPE: str DEFAULT: "output"

readout_kwargs

Extra readout options, such as trainable=True, solver, state_noise or gram_dtype. Architecture dimensions are fixed.

TYPE: dict DEFAULT: None

**reservoir_kwargs

Additional keyword arguments passed to resdag.layers.ESNLayer.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION
`resdag.core.ESNModel`

Configured ESN model ready for training and inference.

Examples:

Simple usage with defaults:

>>> from resdag.models import classic_esn
>>> import torch
>>> model = classic_esn(100, 1, 1)

With custom topology and initializer:

>>> model = classic_esn(
...     reservoir_size=400,
...     feedback_size=1,
...     output_size=1,
...     topology=("watts_strogatz", {"k": 6, "p": 0.1}),
...     feedback_initializer="pseudo_diagonal",
...     spectral_radius=0.9,
...     leak_rate=0.5,
... )

Forward pass:

>>> x = torch.randn(4, 50, 1)  # (batch, time, features)
>>> y = model(x)
See Also

resdag.models.ott_esn : OTT ESN variant resdag.models.linear_esn : Linear ESN variant resdag.training.ESNTrainer : Trainer for fitting readouts

Source code in src/resdag/models/classic_esn.py
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 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
 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
@record_recipe("classic")
def classic_esn(
    reservoir_size: int,
    feedback_size: int,
    output_size: int,
    input_size: int | None = None,
    input_initializer: InitializerSpec | None = None,
    # Reservoir params
    topology: TopologySpec | None = None,
    spectral_radius: float = 0.9,
    leak_rate: float = 1.0,
    noise: float = 0.0,
    feedback_initializer: InitializerSpec | None = None,
    activation: str = "tanh",
    bias: bool = True,
    trainable: bool = False,
    # Readout params
    readout: ReadoutSpec = "ridge",
    readout_alpha: float = 1e-6,
    readout_bias: bool = True,
    readout_name: str = "output",
    readout_kwargs: dict[str, Any] | None = None,
    input_to_readout: bool = True,
    # Extra reservoir kwargs
    **reservoir_kwargs: Any,
) -> ESNModel:
    """Build a classic Echo State Network (ESN) model.

    By default, this architecture concatenates the input with the reservoir
    output before passing to the readout layer. Set `input_to_readout=False`
    to fit the readout on reservoir states alone.

    Architecture:

    ```text
    Input -> Reservoir -> Concatenate(Input, Reservoir) -> Readout
    ```

    The readout sees both the raw input and the reservoir's nonlinear
    transformation, which can improve performance on many tasks.

    Parameters
    ----------
    reservoir_size : int
        Number of units in the reservoir.
    feedback_size : int
        Number of feedback features (input dimension).
    output_size : int
        Number of output features.
    input_size : int or None, optional
        Dimension of an optional driving (exogenous) input.  When given, the
        model takes two inputs `(feedback, driver)` and the driver feeds the
        reservoir alongside the autoregressive feedback.  The driver is kept out
        of the input concatenation, so the readout `in_features` is
        `feedback_size + reservoir_size` when `input_to_readout=True` and
        `reservoir_size` otherwise. `None` (default) builds a
        feedback-only model, unchanged from previous behavior.
    input_initializer : InitializerSpec, optional
        Initializer for the driving-input weights.  Same accepted forms as
        `feedback_initializer`.  Only used when `input_size` is given.
    topology : TopologySpec, optional
        Topology for recurrent weights. Accepts:

        - str: Registry name (e.g., `"erdos_renyi"`)
        - tuple: (name, params) like `("watts_strogatz", {"k": 6, "p": 0.1})`
        - `resdag.init.topology.TopologyInitializer`: Pre-configured object
    spectral_radius : float, default=0.9
        Desired spectral radius for recurrent weights.
    leak_rate : float, default=1.0
        Leaky integration rate (1.0 = no leak).
    noise : float, default=0.0
        Standard deviation of additive Gaussian state noise injected into the
        reservoir after the activation.  Active only in training mode (a no-op
        under `torch.nn.Module.eval`); `0.0` disables it.  Forwarded to
        `resdag.layers.ESNLayer`.  Must be non-negative.
    feedback_initializer : InitializerSpec, optional
        Initializer for feedback weights. Accepts:

        - str: Registry name (e.g., `"pseudo_diagonal"`)
        - tuple: (name, params) like `("chebyshev", {"p": 0.5})`
        - `resdag.init.input_feedback.InputFeedbackInitializer`: Pre-configured object
    activation : str, default="tanh"
        Activation function (`"tanh"`, `"relu"`, `"sigmoid"`, `"identity"`).
    bias : bool, default=True
        Whether to use bias in the reservoir.
    trainable : bool, default=False
        Whether reservoir weights are trainable.
    readout : str or type[ReadoutLayer], default="ridge"
        A built-in name (`"ridge"`, `"cholesky"`, `"cg"`, `"svd"`,
        `"pinv"`, `"incremental"`, `"rls"`, `"fista"`, `"lsmr"`) or a
        `resdag.layers.readouts.ReadoutLayer` subclass. Additional
        solver options go in `readout_kwargs`.
    readout_alpha : float, default=1e-6
        Ridge regression regularization for readout.
    readout_bias : bool, default=True
        Whether to use bias in the readout.
    input_to_readout : bool, default=True
        Whether to append the raw feedback input to the reservoir states seen
        by the readout. Exogenous driving inputs are never appended.
    readout_name : str, default="output"
        Name for the readout layer (used in training targets).
    readout_kwargs : dict, optional
        Extra readout options, such as `trainable=True`, `solver`,
        `state_noise` or `gram_dtype`. Architecture dimensions are fixed.
    **reservoir_kwargs : Any
        Additional keyword arguments passed to `resdag.layers.ESNLayer`.

    Returns
    -------
    `resdag.core.ESNModel`
        Configured ESN model ready for training and inference.

    Examples
    --------
    Simple usage with defaults:

    >>> from resdag.models import classic_esn
    >>> import torch
    >>> model = classic_esn(100, 1, 1)

    With custom topology and initializer:

    >>> model = classic_esn(
    ...     reservoir_size=400,
    ...     feedback_size=1,
    ...     output_size=1,
    ...     topology=("watts_strogatz", {"k": 6, "p": 0.1}),
    ...     feedback_initializer="pseudo_diagonal",
    ...     spectral_radius=0.9,
    ...     leak_rate=0.5,
    ... )

    Forward pass:

    >>> x = torch.randn(4, 50, 1)  # (batch, time, features)
    >>> y = model(x)

    See Also
    --------
    `resdag.models.ott_esn` : OTT ESN variant
    `resdag.models.linear_esn` : Linear ESN variant
    `resdag.training.ESNTrainer` : Trainer for fitting readouts
    """
    if type(input_to_readout) is not bool:
        raise TypeError("input_to_readout must be a bool")
    return _esn_builder(
        reservoir_size=reservoir_size,
        feedback_size=feedback_size,
        output_size=output_size,
        augment=None,
        concat_input=input_to_readout,
        input_size=input_size,
        input_initializer=input_initializer,
        topology=topology,
        spectral_radius=spectral_radius,
        leak_rate=leak_rate,
        noise=noise,
        feedback_initializer=feedback_initializer,
        activation=activation,
        bias=bias,
        trainable=trainable,
        readout=readout,
        readout_alpha=readout_alpha,
        readout_bias=readout_bias,
        readout_name=readout_name,
        readout_kwargs=readout_kwargs,
        **reservoir_kwargs,
    )

coupled_ensemble_esn

coupled_ensemble_esn(
    n_models: int,
    model_factory: Callable[..., ESNModel] = ott_esn,
    aggregate: str | Module = "mean",
    seed: int | None = None,
    **model_kwargs: Any
) -> CoupledEnsembleESNModel

Build a coupled ensemble of N independently-initialized ESN models.

Each sub-model is created by calling model_factory(**model_kwargs) with an independent random reservoir initialization, providing the diversity needed for ensemble averaging to be beneficial.

During autoregressive forecasting all N sub-models receive the same aggregated output (e.g. the mean across models) as their next feedback input — they are coupled through the shared signal.

PARAMETER DESCRIPTION
n_models

Number of sub-models in the ensemble.

TYPE: int

model_factory

Factory that creates one resdag.core.ESNModel. All keyword arguments not consumed by coupled_ensemble_esn itself (i.e. model_kwargs) are forwarded verbatim to every call of this factory. The factory must return a readout-bearing model whose first output dimension equals the feedback input dimension, so the aggregated output can be fed back autoregressively. The readout-bearing premade factories — classic_esn, ott_esn and power_augmented — satisfy this. The headless factories (headless_esn, linear_esn) emit raw reservoir states rather than a feedback-dimensioned output and are rejected by resdag.ensemble.CoupledEnsembleESNModel (see its __init__ for the exact check).

TYPE: callable DEFAULT: `ott_esn`

aggregate

Aggregation strategy applied to the N model outputs at each autoregressive step:

  • "mean" — arithmetic mean.
  • "median" — median.
  • nn.Module — any module accepting a stacked tensor of shape (N, batch, timesteps, features) and returning (batch, timesteps, features). E.g. resdag.ensemble.aggregators.OutliersFilteredMean.

TYPE: str or Module DEFAULT: `"mean"`

seed

Master seed for deterministic sub-model construction. Sub-model i is seeded with seed + i immediately before the factory call. If model_factory itself accepts a seed keyword argument, seed + i is also forwarded as that argument so initialisers that take an explicit seed (e.g. graph topologies) become reproducible.

CPU, available MPS and initialized/requested CUDA RNG states are restored on exit, even if a factory raises. MPS isolation may materialize its host-side generator, but does not create MPS tensors or streams for a CPU factory. Unavailable accelerators and unused CUDA runtimes are not initialized. Subsequent random draws in a larger pipeline are preserved.

TYPE: int DEFAULT: None

**model_kwargs

All remaining keyword arguments are forwarded verbatim to each model_factory call. This includes architecture parameters such as reservoir_size, feedback_size, output_size, spectral_radius, readout_alpha, readout_name, etc. The exact set of valid keys depends on the chosen model_factory.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION
CoupledEnsembleESNModel

Ensemble ready for training and forecasting.

Examples:

Quick start with default Ott's ESN sub-models:

>>> import resdag as rd
>>>
>>> ensemble = rd.coupled_ensemble_esn(
...     n_models=5,
...     reservoir_size=300,
...     feedback_size=3,
...     output_size=3,
... )
>>> ensemble.fit((warmup,), (train,), {"output": targets})
>>> ensemble.reset_reservoirs()
>>> preds = ensemble.forecast(forecast_warmup, horizon=200)
>>> preds.shape
torch.Size([1, 200, 3])

Using classic_esn as the base architecture:

>>> from resdag.models import classic_esn
>>> ensemble = rd.coupled_ensemble_esn(
...     n_models=8,
...     model_factory=classic_esn,
...     reservoir_size=500,
...     feedback_size=3,
...     output_size=3,
...     spectral_radius=0.95,
...     readout_alpha=1e-7,
... )

Outlier-robust aggregation:

>>> from resdag.ensemble.aggregators import OutliersFilteredMean
>>> ensemble = rd.coupled_ensemble_esn(
...     n_models=10,
...     reservoir_size=300,
...     feedback_size=3,
...     output_size=3,
...     aggregate=OutliersFilteredMean(method="z_score", threshold=2.0),
... )

Recovering individual sub-model trajectories for post-hoc analysis:

>>> ensemble.reset_reservoirs()
>>> preds, individuals = ensemble.forecast(
...     forecast_warmup, horizon=200, return_individuals=True
... )
>>> preds.shape          # averaged forecast
torch.Size([1, 200, 3])
>>> len(individuals)     # one tensor per sub-model
10
>>> individuals[0].shape
torch.Size([1, 200, 3])
See Also

CoupledEnsembleESNModel : The ensemble class with full API documentation. resdag.ensemble.aggregators.OutliersFilteredMean : Outlier-robust aggregation layer. resdag.models.ott_esn : Default sub-model factory.

Source code in src/resdag/models/coupled_ensemble_esn.py
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 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
 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
def coupled_ensemble_esn(
    n_models: int,
    model_factory: Callable[..., ESNModel] = ott_esn,
    aggregate: str | nn.Module = "mean",
    seed: int | None = None,
    **model_kwargs: Any,
) -> CoupledEnsembleESNModel:
    """Build a coupled ensemble of N independently-initialized ESN models.

    Each sub-model is created by calling `model_factory(**model_kwargs)`
    with an independent random reservoir initialization, providing the
    diversity needed for ensemble averaging to be beneficial.

    During autoregressive forecasting all N sub-models receive the **same
    aggregated output** (e.g. the mean across models) as their next feedback
    input — they are coupled through the shared signal.

    Parameters
    ----------
    n_models : int
        Number of sub-models in the ensemble.
    model_factory : callable, default `ott_esn`
        Factory that creates one `resdag.core.ESNModel`.
        All keyword arguments not consumed by `coupled_ensemble_esn` itself
        (i.e. `model_kwargs`) are forwarded verbatim to every call of this
        factory.  The factory must return a **readout-bearing** model whose
        first output dimension equals the feedback input dimension, so the
        aggregated output can be fed back autoregressively.  The readout-bearing
        premade factories — `classic_esn`, `ott_esn` and `power_augmented`
        — satisfy this.  The headless factories (`headless_esn`,
        `linear_esn`) emit raw reservoir states rather than a
        feedback-dimensioned output and are rejected by
        `resdag.ensemble.CoupledEnsembleESNModel` (see its `__init__`
        for the exact check).
    aggregate : str or nn.Module, default `"mean"`
        Aggregation strategy applied to the N model outputs at each
        autoregressive step:

        - `"mean"` — arithmetic mean.
        - `"median"` — median.
        - `nn.Module` — any module accepting a stacked tensor of shape
          `(N, batch, timesteps, features)` and returning
          `(batch, timesteps, features)`.  E.g.
          `resdag.ensemble.aggregators.OutliersFilteredMean`.
    seed : int, optional
        Master seed for deterministic sub-model construction.  Sub-model
        `i` is seeded with `seed + i` immediately before the factory call.
        If `model_factory` itself accepts a `seed` keyword argument,
        `seed + i` is also forwarded as that argument so initialisers that
        take an explicit seed (e.g. graph topologies) become reproducible.

        CPU, available MPS and initialized/requested CUDA RNG states are restored
        on exit, even if a factory raises. MPS isolation may materialize its
        host-side generator, but does not create MPS tensors or streams for a
        CPU factory. Unavailable accelerators and unused CUDA runtimes are not
        initialized. Subsequent random draws in a larger pipeline are preserved.

    **model_kwargs
        All remaining keyword arguments are forwarded verbatim to each
        `model_factory` call.  This includes architecture parameters such as
        `reservoir_size`, `feedback_size`, `output_size`,
        `spectral_radius`, `readout_alpha`, `readout_name`, etc.
        The exact set of valid keys depends on the chosen `model_factory`.

    Returns
    -------
    CoupledEnsembleESNModel
        Ensemble ready for training and forecasting.

    Examples
    --------
    Quick start with default Ott's ESN sub-models:

    >>> import resdag as rd
    >>>
    >>> ensemble = rd.coupled_ensemble_esn(
    ...     n_models=5,
    ...     reservoir_size=300,
    ...     feedback_size=3,
    ...     output_size=3,
    ... )
    >>> ensemble.fit((warmup,), (train,), {"output": targets})
    >>> ensemble.reset_reservoirs()
    >>> preds = ensemble.forecast(forecast_warmup, horizon=200)
    >>> preds.shape
    torch.Size([1, 200, 3])

    Using `classic_esn` as the base architecture:

    >>> from resdag.models import classic_esn
    >>> ensemble = rd.coupled_ensemble_esn(
    ...     n_models=8,
    ...     model_factory=classic_esn,
    ...     reservoir_size=500,
    ...     feedback_size=3,
    ...     output_size=3,
    ...     spectral_radius=0.95,
    ...     readout_alpha=1e-7,
    ... )

    Outlier-robust aggregation:

    >>> from resdag.ensemble.aggregators import OutliersFilteredMean
    >>> ensemble = rd.coupled_ensemble_esn(
    ...     n_models=10,
    ...     reservoir_size=300,
    ...     feedback_size=3,
    ...     output_size=3,
    ...     aggregate=OutliersFilteredMean(method="z_score", threshold=2.0),
    ... )

    Recovering individual sub-model trajectories for post-hoc analysis:

    >>> ensemble.reset_reservoirs()
    >>> preds, individuals = ensemble.forecast(
    ...     forecast_warmup, horizon=200, return_individuals=True
    ... )
    >>> preds.shape          # averaged forecast
    torch.Size([1, 200, 3])
    >>> len(individuals)     # one tensor per sub-model
    10
    >>> individuals[0].shape
    torch.Size([1, 200, 3])

    See Also
    --------
    CoupledEnsembleESNModel : The ensemble class with full API documentation.
    resdag.ensemble.aggregators.OutliersFilteredMean : Outlier-robust aggregation layer.
    resdag.models.ott_esn : Default sub-model factory.
    """
    # Detect whether the factory accepts a ``seed`` kwarg so we can forward
    # the per-model seed to initialisers that take an explicit one (graph
    # topologies, etc.). When it doesn't, the per-model RNG seed below still
    # controls every non-seeded random draw.
    factory_accepts_seed = (
        seed is not None and "seed" in inspect.signature(model_factory).parameters
    )

    models: list[ESNModel] = []
    if seed is None:
        # No seeding requested: nothing touches the global RNG beyond what the
        # factory itself draws, so no save/restore dance is needed.
        for _ in range(n_models):
            models.append(model_factory(**model_kwargs))
        return CoupledEnsembleESNModel(models, aggregator=aggregate)

    # Do not broadcast torch.manual_seed to unused accelerator generators.
    # Seed exactly the same CPU stream as before and isolate active/requested
    # accelerator streams with PyTorch's standard context manager.
    target = torch.device(model_kwargs.get("device") or torch.get_default_device())
    cuda_devices = list(range(torch.cuda.device_count())) if torch.cuda.is_initialized() else []
    if target.type == "cuda" and torch.cuda.is_available():
        index = target.index if target.index is not None else torch.cuda.current_device()
        if index not in cuda_devices:
            cuda_devices.append(index)
    # MPS exposes no reliable initialized-state query: native random operations
    # need not populate Python's generator cache. Fork its available generator
    # using the public API; snapshotting that state is host-side bookkeeping.
    isolate_mps = torch.backends.mps.is_available()
    with ExitStack() as isolation:
        isolation.enter_context(torch.random.fork_rng(devices=cuda_devices))
        if isolate_mps:
            isolation.enter_context(torch.random.fork_rng(devices=[0], device_type="mps"))
        for i in range(n_models):
            sub_seed = seed + i
            torch.default_generator.manual_seed(sub_seed)
            for index in cuda_devices:
                torch.cuda.default_generators[index].manual_seed(sub_seed)
            if isolate_mps:
                torch.mps.manual_seed(sub_seed)
            kwargs = dict(model_kwargs)
            if factory_accepts_seed:
                kwargs.setdefault("seed", sub_seed)
            models.append(model_factory(**kwargs))
    return CoupledEnsembleESNModel(models, aggregator=aggregate)

deep_esn

deep_esn(
    reservoir_sizes: Sequence[int] | int,
    n_layers: int | None = None,
    feedback_size: int = 1,
    output_size: int = 1,
    *,
    concat_all_states: bool = True,
    interlayer_scaling: float = 0.5,
    topology: TopologySpec | None = None,
    spectral_radius: float = 0.9,
    leak_rate: float | Sequence[float] = 1.0,
    feedback_initializer: InitializerSpec | None = None,
    activation: str = "tanh",
    bias: bool = True,
    trainable: bool = False,
    readout: ReadoutSpec = "ridge",
    readout_alpha: float = 1e-06,
    readout_bias: bool = True,
    readout_name: str = "output",
    readout_kwargs: dict[str, Any] | None = None,
    **reservoir_kwargs: Any
) -> ESNModel

Build a Deep (hierarchical, stacked-reservoir) Echo State Network.

Stacks N reservoir layers so that layer i's state sequence is the feedback input of layer i + 1. The readout, by default, is fitted on the concatenation of all layers' states — the standard DeepESN readout — so it can exploit the progressively slower, more structured memory timescales the deeper layers develop. Set concat_all_states=False to read out from the last layer alone.

Architecture (concat_all_states=True):

Input -> Reservoir_1 -> Reservoir_2 -> ... -> Reservoir_N
             |              |                     |
             +--------------+----- Concatenate ---+---> Readout

Only the first layer receives the raw feedback; every subsequent layer's feedback dimension is the previous layer's reservoir_size.

PARAMETER DESCRIPTION
reservoir_sizes

Per-layer reservoir sizes as a list (one entry per layer), or a single int broadcast to all n_layers layers. When a single int is given, n_layers is required.

TYPE: sequence of int or int

n_layers

Number of stacked layers. Required when reservoir_sizes is a single int; ignored (but must be consistent) when reservoir_sizes is a list.

TYPE: int or None DEFAULT: None

feedback_size

Number of feedback features driving the first layer (the input dimension of the model).

TYPE: int DEFAULT: 1

output_size

Number of output features. For autoregressive forecast, this must equal feedback_size (the first model output is fed back).

TYPE: int DEFAULT: 1

concat_all_states

When True (the standard DeepESN readout) the readout sees the concatenation of every layer's state, so its in_features is sum(reservoir_sizes). When False the readout sees only the last layer's state, so in_features is reservoir_sizes[-1].

TYPE: bool DEFAULT: True

interlayer_scaling

Magnitude of the inter-layer coupling weights (layers 2..N). Each deeper layer's feedback is the previous layer's high-dimensional state, so the default uniform(-1, 1) feedback weights would over-saturate the tanh; scaling them down (via a uniform(-interlayer_scaling, interlayer_scaling) initializer) keeps the deeper reservoirs in their useful dynamic range. Applied only when feedback_initializer is left as None; an explicit feedback_initializer is used verbatim on every layer and this knob is ignored. The first layer always uses the raw (unscaled) input path.

TYPE: float DEFAULT: 0.5

topology

Topology for the recurrent weights, shared by every layer. Accepts a registry name, a (name, params) tuple, a callable, or a configured resdag.init.topology.TopologyInitializer.

TYPE: TopologySpec DEFAULT: None

spectral_radius

Target spectral radius for the recurrent weights of every layer.

TYPE: float DEFAULT: 0.9

leak_rate

Leaky-integration rate. A scalar is shared by every layer; a list (one entry per layer) sets a per-layer schedule. The DeepESN literature recommends leak rates that decrease with depth — fast dynamics near the input, slow dynamics deep in the stack — e.g. leak_rate=[1.0, 0.7, 0.4] for a 3-layer network.

TYPE: float or sequence of float DEFAULT: 1.0

feedback_initializer

Initializer for the feedback weights, shared by every layer. Same accepted forms as topology.

TYPE: InitializerSpec DEFAULT: None

activation

Activation function for every layer ("tanh", "relu", "sigmoid", "identity").

TYPE: str DEFAULT: "tanh"

bias

Whether every reservoir layer uses a bias term.

TYPE: bool DEFAULT: True

trainable

Whether the reservoir weights are trainable.

TYPE: bool DEFAULT: False

readout

A built-in name ("ridge", "cholesky", "cg", "svd", "pinv", "incremental", "rls", "fista", "lsmr") or a resdag.layers.readouts.ReadoutLayer subclass. Additional solver options go in readout_kwargs.

TYPE: str or type[ReadoutLayer] DEFAULT: "ridge"

readout_alpha

Ridge regression regularization for the readout.

TYPE: float DEFAULT: 1e-6

readout_bias

Whether the readout uses a bias term.

TYPE: bool DEFAULT: True

readout_name

Name for the readout layer (used as the target key in training).

TYPE: str DEFAULT: "output"

readout_kwargs

Extra readout options, such as trainable=True, solver, state_noise or gram_dtype. Architecture dimensions are fixed.

TYPE: dict DEFAULT: None

**reservoir_kwargs

Additional keyword arguments forwarded to every resdag.layers.ESNLayer.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION
`resdag.core.ESNModel`

The assembled deep ESN, ready for training and forecasting.

RAISES DESCRIPTION
ValueError

If the layer stack is empty, a reservoir size is not a positive integer, reservoir_sizes is a scalar without n_layers, the per-layer leak_rate schedule length does not match the number of layers, or output_size is not a positive integer.

Notes

The stack is untrained like a standard ESN — depth adds temporal richness without any extra gradient training; only the readout is fitted (by ridge regression). Depth is not a free win over a single wide reservoir: on a short, single-timescale task (e.g. a brief Lorenz-63 window) a single classic_esn of the combined width usually forecasts further, because one large reservoir already spans the needed dynamics. DeepESN pays off on multi-timescale / hierarchical signals — where a decreasing-with-depth leak schedule (see leak_rate below) lets successive layers specialise on progressively slower dynamics (Gallicchio & Micheli 2017; the layer-specific time-scale separation of Frontiers in AI 2024). Reach for it when the signal has structure at several timescales, not as a drop-in replacement for a wide ESN.

Examples:

A 3-layer stack of equal width with a decreasing-with-depth leak schedule::

>>> from resdag.models import deep_esn
>>> model = deep_esn(
...     reservoir_sizes=300,
...     n_layers=3,
...     feedback_size=3,
...     output_size=3,
...     leak_rate=[1.0, 0.6, 0.3],
...     spectral_radius=0.9,
... )

Explicit per-layer sizes (narrowing with depth), reading out from the last layer only::

>>> model = deep_esn(
...     reservoir_sizes=[400, 200, 100],
...     feedback_size=3,
...     output_size=3,
...     concat_all_states=False,
... )

Training and forecasting are identical to any other premade model::

>>> from resdag.training import ESNTrainer
>>> trainer = ESNTrainer(model)
>>> trainer.fit(
...     warmup_inputs=(warmup,),
...     train_inputs=(train,),
...     targets={"output": target},
... )
>>> predictions = model.forecast(warmup, horizon=500)
See Also

classic_esn : Single-reservoir ESN with input concatenation. hybrid_esn : Physics-prior hybrid ESN. resdag.training.ESNTrainer : Trainer for fitting the readout.

Source code in src/resdag/models/deep_esn.py
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
def deep_esn(
    reservoir_sizes: Sequence[int] | int,
    n_layers: int | None = None,
    feedback_size: int = 1,
    output_size: int = 1,
    *,
    concat_all_states: bool = True,
    interlayer_scaling: float = 0.5,
    # Reservoir params
    topology: TopologySpec | None = None,
    spectral_radius: float = 0.9,
    leak_rate: float | Sequence[float] = 1.0,
    feedback_initializer: InitializerSpec | None = None,
    activation: str = "tanh",
    bias: bool = True,
    trainable: bool = False,
    # Readout params
    readout: ReadoutSpec = "ridge",
    readout_alpha: float = 1e-6,
    readout_bias: bool = True,
    readout_name: str = "output",
    readout_kwargs: dict[str, Any] | None = None,
    # Extra reservoir kwargs
    **reservoir_kwargs: Any,
) -> ESNModel:
    """Build a Deep (hierarchical, stacked-reservoir) Echo State Network.

    Stacks `N` reservoir layers so that layer `i`'s state sequence is the
    feedback input of layer `i + 1`.  The readout, by default, is fitted on the
    **concatenation of all layers' states** — the standard DeepESN readout — so
    it can exploit the progressively slower, more structured memory timescales
    the deeper layers develop.  Set `concat_all_states=False` to read out from
    the last layer alone.

    Architecture (`concat_all_states=True`):

    ```text
    Input -> Reservoir_1 -> Reservoir_2 -> ... -> Reservoir_N
                 |              |                     |
                 +--------------+----- Concatenate ---+---> Readout
    ```

    Only the first layer receives the raw feedback; every subsequent layer's
    feedback dimension is the previous layer's `reservoir_size`.

    Parameters
    ----------
    reservoir_sizes : sequence of int or int
        Per-layer reservoir sizes as a list (one entry per layer), or a single
        int broadcast to all `n_layers` layers.  When a single int is given,
        `n_layers` is required.
    n_layers : int or None, optional
        Number of stacked layers.  Required when `reservoir_sizes` is a single
        int; ignored (but must be consistent) when `reservoir_sizes` is a list.
    feedback_size : int, default=1
        Number of feedback features driving the *first* layer (the input
        dimension of the model).
    output_size : int, default=1
        Number of output features.  For autoregressive `forecast`, this
        must equal `feedback_size` (the first model output is fed back).
    concat_all_states : bool, default=True
        When `True` (the standard DeepESN readout) the readout sees the
        concatenation of every layer's state, so its `in_features` is
        `sum(reservoir_sizes)`.  When `False` the readout sees only the last
        layer's state, so `in_features` is `reservoir_sizes[-1]`.
    interlayer_scaling : float, default=0.5
        Magnitude of the inter-layer coupling weights (layers `2..N`).  Each
        deeper layer's feedback is the *previous layer's high-dimensional state*,
        so the default `uniform(-1, 1)` feedback weights would over-saturate the
        `tanh`; scaling them down (via a `uniform(-interlayer_scaling, interlayer_scaling)` initializer) keeps the deeper reservoirs in their
        useful dynamic range.  Applied only when `feedback_initializer` is left
        as `None`; an explicit `feedback_initializer` is used verbatim on
        every layer and this knob is ignored.  The first layer always uses the raw
        (unscaled) input path.
    topology : TopologySpec, optional
        Topology for the recurrent weights, shared by every layer.  Accepts a
        registry name, a `(name, params)` tuple, a callable, or a configured
        `resdag.init.topology.TopologyInitializer`.
    spectral_radius : float, default=0.9
        Target spectral radius for the recurrent weights of every layer.
    leak_rate : float or sequence of float, default=1.0
        Leaky-integration rate.  A scalar is shared by every layer; a list (one
        entry per layer) sets a per-layer schedule.  The DeepESN literature
        recommends leak rates that **decrease with depth** — fast dynamics near
        the input, slow dynamics deep in the stack — e.g.
        `leak_rate=[1.0, 0.7, 0.4]` for a 3-layer network.
    feedback_initializer : InitializerSpec, optional
        Initializer for the feedback weights, shared by every layer.  Same
        accepted forms as `topology`.
    activation : str, default="tanh"
        Activation function for every layer (`"tanh"`, `"relu"`,
        `"sigmoid"`, `"identity"`).
    bias : bool, default=True
        Whether every reservoir layer uses a bias term.
    trainable : bool, default=False
        Whether the reservoir weights are trainable.
    readout : str or type[ReadoutLayer], default="ridge"
        A built-in name (`"ridge"`, `"cholesky"`, `"cg"`, `"svd"`,
        `"pinv"`, `"incremental"`, `"rls"`, `"fista"`, `"lsmr"`) or a
        `resdag.layers.readouts.ReadoutLayer` subclass. Additional
        solver options go in `readout_kwargs`.
    readout_alpha : float, default=1e-6
        Ridge regression regularization for the readout.
    readout_bias : bool, default=True
        Whether the readout uses a bias term.
    readout_name : str, default="output"
        Name for the readout layer (used as the target key in training).
    readout_kwargs : dict, optional
        Extra readout options, such as `trainable=True`, `solver`,
        `state_noise` or `gram_dtype`. Architecture dimensions are fixed.
    **reservoir_kwargs : Any
        Additional keyword arguments forwarded to **every**
        `resdag.layers.ESNLayer`.

    Returns
    -------
    `resdag.core.ESNModel`
        The assembled deep ESN, ready for training and forecasting.

    Raises
    ------
    ValueError
        If the layer stack is empty, a reservoir size is not a positive integer,
        `reservoir_sizes` is a scalar without `n_layers`, the per-layer
        `leak_rate` schedule length does not match the number of layers, or
        `output_size` is not a positive integer.

    Notes
    -----
    The stack is *untrained* like a standard ESN — depth adds temporal richness
    without any extra gradient training; only the readout is fitted (by ridge
    regression).  Depth is not a free win over a single wide reservoir: on a
    short, single-timescale task (e.g. a brief Lorenz-63 window) a single
    `classic_esn` of the combined width usually forecasts *further*, because
    one large reservoir already spans the needed dynamics.  DeepESN pays off on
    **multi-timescale / hierarchical** signals — where a decreasing-with-depth
    leak schedule (see `leak_rate` below) lets successive layers specialise on
    progressively slower dynamics (Gallicchio & Micheli 2017; the layer-specific
    time-scale separation of Frontiers in AI 2024).  Reach for it when the signal
    has structure at several timescales, not as a drop-in replacement for a wide
    ESN.

    Examples
    --------
    A 3-layer stack of equal width with a decreasing-with-depth leak schedule::

    >>> from resdag.models import deep_esn
    >>> model = deep_esn(
    ...     reservoir_sizes=300,
    ...     n_layers=3,
    ...     feedback_size=3,
    ...     output_size=3,
    ...     leak_rate=[1.0, 0.6, 0.3],
    ...     spectral_radius=0.9,
    ... )

    Explicit per-layer sizes (narrowing with depth), reading out from the last
    layer only::

    >>> model = deep_esn(
    ...     reservoir_sizes=[400, 200, 100],
    ...     feedback_size=3,
    ...     output_size=3,
    ...     concat_all_states=False,
    ... )

    Training and forecasting are identical to any other premade model::

    >>> from resdag.training import ESNTrainer
    >>> trainer = ESNTrainer(model)
    >>> trainer.fit(
    ...     warmup_inputs=(warmup,),
    ...     train_inputs=(train,),
    ...     targets={"output": target},
    ... )
    >>> predictions = model.forecast(warmup, horizon=500)

    See Also
    --------
    classic_esn : Single-reservoir ESN with input concatenation.
    hybrid_esn : Physics-prior hybrid ESN.
    resdag.training.ESNTrainer : Trainer for fitting the readout.
    """
    sizes = _resolve_reservoir_sizes(reservoir_sizes, n_layers)
    leak_rates = _broadcast_leak_rates(leak_rate, len(sizes))

    if not isinstance(output_size, int) or output_size <= 0:
        raise ValueError(f"deep_esn: output_size must be a positive integer, got {output_size!r}.")

    # Resolve the readout spec up front so an invalid one fails before any
    # partial construction.

    inp = reservoir_input(
        feedback_size, dtype=reservoir_kwargs.get("dtype"), device=reservoir_kwargs.get("device")
    )

    # Build the stack: layer i takes the previous layer's state as its feedback,
    # so its feedback dimension is the previous reservoir_size (feedback_size for
    # the first layer). Collect every layer's state for the concat-all readout.
    layer_states = []
    prev_output = inp
    prev_feedback_size = feedback_size
    for i, (size, layer_leak) in enumerate(zip(sizes, leak_rates)):
        # First layer sees the raw input (user's feedback_initializer); deeper
        # layers see a high-dimensional reservoir state, so scale their coupling
        # down (unless the user pinned an explicit feedback_initializer).
        if i == 0 or feedback_initializer is not None:
            layer_feedback_init = feedback_initializer
        else:
            layer_feedback_init = (
                "uniform",
                {"low": -interlayer_scaling, "high": interlayer_scaling},
            )
        state = ESNLayer(
            reservoir_size=size,
            feedback_size=prev_feedback_size,
            topology=topology,
            spectral_radius=spectral_radius,
            leak_rate=layer_leak,
            feedback_initializer=layer_feedback_init,
            activation=activation,
            bias=bias,
            trainable=trainable,
            **reservoir_kwargs,
        )(prev_output)
        layer_states.append(state)
        prev_output = state
        prev_feedback_size = size

    # Standard DeepESN readout: concatenate every layer's state. When
    # concat_all_states is False, read out from the last layer alone.
    if concat_all_states and len(layer_states) > 1:
        features = Concatenate()(*layer_states)
        readout_in_features = sum(sizes)
    else:
        features = layer_states[-1]
        readout_in_features = sizes[-1]

    readout_layer = _make_readout(
        readout,
        in_features=readout_in_features,
        out_features=output_size,
        bias=readout_bias,
        alpha=readout_alpha,
        name=readout_name,
        readout_kwargs=readout_kwargs,
    ).to(device=reservoir_kwargs.get("device"), dtype=reservoir_kwargs.get("dtype"))(features)

    return ESNModel(inp, readout_layer)

es2n

es2n(
    reservoir_size: int,
    feedback_size: int,
    output_size: int,
    beta: float = 0.9,
    input_size: int | None = None,
    input_initializer: InitializerSpec | None = None,
    topology: TopologySpec | None = None,
    spectral_radius: float = 0.9,
    orthogonal_scaling: float = 1.0,
    feedback_initializer: InitializerSpec | None = None,
    activation: str = "tanh",
    bias: bool = True,
    trainable: bool = False,
    readout: ReadoutSpec = "ridge",
    readout_alpha: float = 1e-06,
    readout_bias: bool = True,
    readout_name: str = "output",
    readout_kwargs: dict[str, Any] | None = None,
    **reservoir_kwargs: Any
) -> ESNModel

Build an Edge-of-Stability State Network (ES2N) model.

ES2N (Ceni & Gallicchio, arXiv:2308.02902) replaces the leaky-ESN state update with a convex combination of a nonlinear ESN branch and a fixed random orthogonal skip:

\[ x_t = \beta\,\phi(W_r x_{t-1} + \cdots) + (1 - \beta)\,O\,x_{t-1} \]

Small beta sits the reservoir near the edge of stability (orthogonal, norm-preserving, long memory); beta = 1 recovers a standard ESN. This factory wires the same input-concatenation architecture as resdag.models.classic_esn:

Input -> ES2N Reservoir -> Concatenate(Input, Reservoir) -> Readout
PARAMETER DESCRIPTION
reservoir_size

Number of units in the reservoir.

TYPE: int

feedback_size

Number of feedback features (autoregressive input dimension).

TYPE: int

output_size

Number of output features.

TYPE: int

beta

Proximity to the edge of stability in \((0, 1]\). Smaller values weight the orthogonal skip (longer memory); 1.0 recovers a standard non-leaky ESN. For chaotic-system forecasting, smaller beta (e.g. 0.1--0.3) is typically preferred.

TYPE: float DEFAULT: 0.9

input_size

Dimension of an optional driving (exogenous) input. When given, the model takes two inputs (feedback, driver); the driver is kept out of the input concatenation. None (default) builds a feedback-only model.

TYPE: int or None DEFAULT: None

input_initializer

Initializer for the driving-input weights. Only used when input_size is given.

TYPE: InitializerSpec DEFAULT: None

topology

Topology for the recurrent weights W_r. Accepts a registry name, a (name, params) tuple, a callable, or a pre-configured resdag.init.topology.TopologyInitializer.

TYPE: TopologySpec DEFAULT: None

spectral_radius

Target spectral radius for the recurrent weights W_r.

TYPE: float DEFAULT: 0.9

orthogonal_scaling

Gain on the orthogonal skip matrix O. 1.0 keeps it exactly norm-preserving (the edge-of-stability regime).

TYPE: float DEFAULT: 1.0

feedback_initializer

Initializer for the feedback weights.

TYPE: InitializerSpec DEFAULT: None

activation

Activation for the nonlinear branch.

TYPE: (tanh, relu, sigmoid, identity) DEFAULT: 'tanh'

bias

Whether to use a bias in the reservoir.

TYPE: bool DEFAULT: True

trainable

Whether the reservoir weights are trainable. The orthogonal skip stays frozen regardless.

TYPE: bool DEFAULT: False

readout

A built-in name ("ridge", "cholesky", "cg", "svd", "pinv", "incremental", "rls", "fista", "lsmr") or a resdag.layers.readouts.ReadoutLayer subclass. Additional solver options go in readout_kwargs.

TYPE: str or type[ReadoutLayer] DEFAULT: "ridge"

readout_alpha

Ridge regularization for the readout.

TYPE: float DEFAULT: 1e-6

readout_bias

Whether to use a bias in the readout.

TYPE: bool DEFAULT: True

readout_name

Name for the readout layer (used as the target key in training).

TYPE: str DEFAULT: "output"

readout_kwargs

Extra readout options, such as trainable=True, solver, state_noise or gram_dtype. Architecture dimensions are fixed.

TYPE: dict DEFAULT: None

**reservoir_kwargs

Additional keyword arguments forwarded to resdag.layers.reservoirs.es2n.ES2NLayer (e.g. bias_scaling, seed).

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION
`resdag.core.ESNModel`

Configured ES2N model ready for training and inference.

Examples:

>>> from resdag.models import es2n
>>> model = es2n(reservoir_size=500, feedback_size=3, output_size=3, beta=0.1)
See Also

resdag.models.resesn : Residual ESN (decoupled skip / nonlinear weights). resdag.models.classic_esn : Traditional leaky ESN. resdag.layers.reservoirs.es2n.ES2NLayer : The reservoir layer.

Source code in src/resdag/models/es2n.py
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 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
 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
def es2n(
    reservoir_size: int,
    feedback_size: int,
    output_size: int,
    beta: float = 0.9,
    input_size: int | None = None,
    input_initializer: InitializerSpec | None = None,
    # Reservoir params
    topology: TopologySpec | None = None,
    spectral_radius: float = 0.9,
    orthogonal_scaling: float = 1.0,
    feedback_initializer: InitializerSpec | None = None,
    activation: str = "tanh",
    bias: bool = True,
    trainable: bool = False,
    # Readout params
    readout: ReadoutSpec = "ridge",
    readout_alpha: float = 1e-6,
    readout_bias: bool = True,
    readout_name: str = "output",
    readout_kwargs: dict[str, Any] | None = None,
    # Extra reservoir kwargs
    **reservoir_kwargs: Any,
) -> ESNModel:
    r"""Build an Edge-of-Stability State Network (ES2N) model.

    ES2N (Ceni & Gallicchio, arXiv:2308.02902) replaces the leaky-ESN state
    update with a convex combination of a nonlinear ESN branch and a fixed
    random *orthogonal* skip:

    $$
    x_t = \beta\,\phi(W_r x_{t-1} + \cdots) + (1 - \beta)\,O\,x_{t-1}
    $$

    Small `beta` sits the reservoir near the edge of stability (orthogonal,
    norm-preserving, long memory); `beta = 1` recovers a standard ESN.  This
    factory wires the same input-concatenation architecture as
    `resdag.models.classic_esn`:

    ```text
    Input -> ES2N Reservoir -> Concatenate(Input, Reservoir) -> Readout
    ```

    Parameters
    ----------
    reservoir_size : int
        Number of units in the reservoir.
    feedback_size : int
        Number of feedback features (autoregressive input dimension).
    output_size : int
        Number of output features.
    beta : float, default=0.9
        Proximity to the edge of stability in $(0, 1]$.  Smaller values
        weight the orthogonal skip (longer memory); `1.0` recovers a standard
        non-leaky ESN.  For chaotic-system forecasting, smaller `beta` (e.g.
        0.1--0.3) is typically preferred.
    input_size : int or None, optional
        Dimension of an optional driving (exogenous) input.  When given, the
        model takes two inputs `(feedback, driver)`; the driver is kept out of
        the input concatenation.  `None` (default) builds a feedback-only
        model.
    input_initializer : InitializerSpec, optional
        Initializer for the driving-input weights.  Only used when
        `input_size` is given.
    topology : TopologySpec, optional
        Topology for the recurrent weights `W_r`.  Accepts a registry name, a
        `(name, params)` tuple, a callable, or a pre-configured
        `resdag.init.topology.TopologyInitializer`.
    spectral_radius : float, default=0.9
        Target spectral radius for the recurrent weights `W_r`.
    orthogonal_scaling : float, default=1.0
        Gain on the orthogonal skip matrix `O`.  `1.0` keeps it exactly
        norm-preserving (the edge-of-stability regime).
    feedback_initializer : InitializerSpec, optional
        Initializer for the feedback weights.
    activation : {'tanh', 'relu', 'sigmoid', 'identity'}, default='tanh'
        Activation for the nonlinear branch.
    bias : bool, default=True
        Whether to use a bias in the reservoir.
    trainable : bool, default=False
        Whether the reservoir weights are trainable.  The orthogonal skip stays
        frozen regardless.
    readout : str or type[ReadoutLayer], default="ridge"
        A built-in name (`"ridge"`, `"cholesky"`, `"cg"`, `"svd"`,
        `"pinv"`, `"incremental"`, `"rls"`, `"fista"`, `"lsmr"`) or a
        `resdag.layers.readouts.ReadoutLayer` subclass. Additional
        solver options go in `readout_kwargs`.
    readout_alpha : float, default=1e-6
        Ridge regularization for the readout.
    readout_bias : bool, default=True
        Whether to use a bias in the readout.
    readout_name : str, default="output"
        Name for the readout layer (used as the target key in training).
    readout_kwargs : dict, optional
        Extra readout options, such as `trainable=True`, `solver`,
        `state_noise` or `gram_dtype`. Architecture dimensions are fixed.
    **reservoir_kwargs : Any
        Additional keyword arguments forwarded to
        `resdag.layers.reservoirs.es2n.ES2NLayer` (e.g. `bias_scaling`,
        `seed`).

    Returns
    -------
    `resdag.core.ESNModel`
        Configured ES2N model ready for training and inference.

    Examples
    --------
    >>> from resdag.models import es2n
    >>> model = es2n(reservoir_size=500, feedback_size=3, output_size=3, beta=0.1)

    See Also
    --------
    resdag.models.resesn : Residual ESN (decoupled skip / nonlinear weights).
    resdag.models.classic_esn : Traditional leaky ESN.
    resdag.layers.reservoirs.es2n.ES2NLayer : The reservoir layer.
    """
    return _esn_builder(
        reservoir_size=reservoir_size,
        feedback_size=feedback_size,
        output_size=output_size,
        augment=None,
        concat_input=True,
        input_size=input_size,
        input_initializer=input_initializer,
        reservoir_cls=ES2NLayer,
        topology=topology,
        spectral_radius=spectral_radius,
        feedback_initializer=feedback_initializer,
        activation=activation,
        bias=bias,
        trainable=trainable,
        readout=readout,
        readout_alpha=readout_alpha,
        readout_bias=readout_bias,
        readout_name=readout_name,
        readout_kwargs=readout_kwargs,
        beta=beta,
        orthogonal_scaling=orthogonal_scaling,
        **reservoir_kwargs,
    )

eusn

eusn(
    reservoir_size: int,
    feedback_size: int,
    output_size: int,
    epsilon: float = 0.01,
    gamma: float = 0.01,
    input_size: int | None = None,
    input_initializer: InitializerSpec | None = None,
    topology: TopologySpec | None = None,
    spectral_radius: float = 0.9,
    substeps: int = 1,
    solver: str = "euler",
    feedback_initializer: InitializerSpec | None = None,
    activation: str = "tanh",
    bias: bool = True,
    trainable: bool = False,
    readout: ReadoutSpec = "ridge",
    readout_alpha: float = 1e-06,
    readout_bias: bool = True,
    readout_name: str = "output",
    readout_kwargs: dict[str, Any] | None = None,
    **reservoir_kwargs: Any
) -> ESNModel

Build an Euler State Network (EuSN) model.

EuSN (Gallicchio, arXiv:2203.09382) replaces the leaky-ESN state update with one forward-Euler step of an ODE whose recurrent matrix is antisymmetric (norm-preserving) minus a small diffusion term:

\[ h_t = h_{t-1} + \varepsilon\, \tanh\!\big((W_r - W_r^\top - \gamma I)\, h_{t-1} + \cdots\big). \]

Small \(\varepsilon\) and \(\gamma\) sit the reservoir near the edge of stability (non-dissipative, long memory). This factory wires the same input-concatenation architecture as resdag.models.classic_esn:

Input -> EuSN Reservoir -> Concatenate(Input, Reservoir) -> Readout
PARAMETER DESCRIPTION
reservoir_size

Number of units in the reservoir.

TYPE: int

feedback_size

Number of feedback features (autoregressive input dimension).

TYPE: int

output_size

Number of output features.

TYPE: int

epsilon

Forward-Euler step size \(\varepsilon\). Smaller values sit the reservoir closer to the edge of stability (longer, near-lossless memory).

TYPE: float DEFAULT: 0.01

gamma

Diffusion coefficient \(\gamma \ge 0\) damping the Euler discretization error. 0.0 recovers the undamped antisymmetric flow.

TYPE: float DEFAULT: 0.01

input_size

Dimension of an optional driving (exogenous) input. When given, the model takes two inputs (feedback, driver); the driver is kept out of the input concatenation. None (default) builds a feedback-only model.

TYPE: int or None DEFAULT: None

input_initializer

Initializer for the driving-input weights. Only used when input_size is given.

TYPE: InitializerSpec DEFAULT: None

topology

Topology for the recurrent weights W_r (antisymmetrized on the fly by the cell). Accepts a registry name, a (name, params) tuple, a callable, or a pre-configured resdag.init.topology.TopologyInitializer.

TYPE: TopologySpec DEFAULT: None

spectral_radius

Target rotation rate for W_r (largest imaginary-eigenvalue magnitude of the antisymmetric part).

TYPE: float DEFAULT: 0.9

substeps

Fixed integration sub-steps per interval. 1 is the single forward-Euler step of the paper.

TYPE: int DEFAULT: 1

solver

Integration scheme. 'euler' is the paper's method; 'rk4' and the adaptive 'torchdiffeq' (requires resdag[ode]) integrate the same field more accurately.

TYPE: (euler, rk4, torchdiffeq) DEFAULT: 'euler'

feedback_initializer

Initializer for the feedback weights.

TYPE: InitializerSpec DEFAULT: None

activation

Activation of the vector field (tanh is the EuSN choice).

TYPE: (tanh, relu, sigmoid, identity) DEFAULT: 'tanh'

bias

Whether to use a bias in the reservoir.

TYPE: bool DEFAULT: True

trainable

Whether the reservoir weights are trainable.

TYPE: bool DEFAULT: False

readout

A built-in name ("ridge", "cholesky", "cg", "svd", "pinv", "incremental", "rls", "fista", "lsmr") or a resdag.layers.readouts.ReadoutLayer subclass. Additional solver options go in readout_kwargs.

TYPE: str or type[ReadoutLayer] DEFAULT: "ridge"

readout_alpha

Ridge regularization for the readout.

TYPE: float DEFAULT: 1e-6

readout_bias

Whether to use a bias in the readout.

TYPE: bool DEFAULT: True

readout_name

Name for the readout layer (used as the target key in training).

TYPE: str DEFAULT: "output"

readout_kwargs

Extra readout options, such as trainable=True, solver, state_noise or gram_dtype. Architecture dimensions are fixed.

TYPE: dict DEFAULT: None

**reservoir_kwargs

Additional keyword arguments forwarded to resdag.layers.reservoirs.eusn.EuSNLayer (e.g. bias_scaling, seed, torchdiffeq_method).

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION
`resdag.core.ESNModel`

Configured EuSN model ready for training and inference.

Examples:

>>> from resdag.models import eusn
>>> model = eusn(
...     reservoir_size=500, feedback_size=3, output_size=3,
...     epsilon=0.01, gamma=0.01,
... )
See Also

resdag.models.es2n : Edge-of-Stability State Network (discrete orthogonal skip). resdag.models.classic_esn : Traditional leaky ESN. resdag.layers.reservoirs.eusn.EuSNLayer : The reservoir layer.

Source code in src/resdag/models/eusn.py
 44
 45
 46
 47
 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
 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
def eusn(
    reservoir_size: int,
    feedback_size: int,
    output_size: int,
    epsilon: float = 0.01,
    gamma: float = 0.01,
    input_size: int | None = None,
    input_initializer: InitializerSpec | None = None,
    # Reservoir params
    topology: TopologySpec | None = None,
    spectral_radius: float = 0.9,
    substeps: int = 1,
    solver: str = "euler",
    feedback_initializer: InitializerSpec | None = None,
    activation: str = "tanh",
    bias: bool = True,
    trainable: bool = False,
    # Readout params
    readout: ReadoutSpec = "ridge",
    readout_alpha: float = 1e-6,
    readout_bias: bool = True,
    readout_name: str = "output",
    readout_kwargs: dict[str, Any] | None = None,
    # Extra reservoir kwargs
    **reservoir_kwargs: Any,
) -> ESNModel:
    r"""Build an Euler State Network (EuSN) model.

    EuSN (Gallicchio, arXiv:2203.09382) replaces the leaky-ESN state update with
    one forward-Euler step of an ODE whose recurrent matrix is antisymmetric
    (norm-preserving) minus a small diffusion term:

    $$
    h_t = h_{t-1} + \varepsilon\,
          \tanh\!\big((W_r - W_r^\top - \gamma I)\, h_{t-1} + \cdots\big).
    $$

    Small $\varepsilon$ and $\gamma$ sit the reservoir near the edge
    of stability (non-dissipative, long memory).  This factory wires the same
    input-concatenation architecture as `resdag.models.classic_esn`:

    ```text
    Input -> EuSN Reservoir -> Concatenate(Input, Reservoir) -> Readout
    ```

    Parameters
    ----------
    reservoir_size : int
        Number of units in the reservoir.
    feedback_size : int
        Number of feedback features (autoregressive input dimension).
    output_size : int
        Number of output features.
    epsilon : float, default=0.01
        Forward-Euler step size $\varepsilon$.  Smaller values sit the
        reservoir closer to the edge of stability (longer, near-lossless
        memory).
    gamma : float, default=0.01
        Diffusion coefficient $\gamma \ge 0$ damping the Euler
        discretization error.  `0.0` recovers the undamped antisymmetric flow.
    input_size : int or None, optional
        Dimension of an optional driving (exogenous) input.  When given, the
        model takes two inputs `(feedback, driver)`; the driver is kept out of
        the input concatenation.  `None` (default) builds a feedback-only
        model.
    input_initializer : InitializerSpec, optional
        Initializer for the driving-input weights.  Only used when
        `input_size` is given.
    topology : TopologySpec, optional
        Topology for the recurrent weights `W_r` (antisymmetrized on the fly
        by the cell).  Accepts a registry name, a `(name, params)` tuple, a
        callable, or a pre-configured
        `resdag.init.topology.TopologyInitializer`.
    spectral_radius : float, default=0.9
        Target rotation rate for `W_r` (largest imaginary-eigenvalue magnitude
        of the antisymmetric part).
    substeps : int, default=1
        Fixed integration sub-steps per interval.  `1` is the single
        forward-Euler step of the paper.
    solver : {'euler', 'rk4', 'torchdiffeq'}, default='euler'
        Integration scheme.  `'euler'` is the paper's method; `'rk4'` and
        the adaptive `'torchdiffeq'` (requires `resdag[ode]`) integrate the
        same field more accurately.
    feedback_initializer : InitializerSpec, optional
        Initializer for the feedback weights.
    activation : {'tanh', 'relu', 'sigmoid', 'identity'}, default='tanh'
        Activation of the vector field (`tanh` is the EuSN choice).
    bias : bool, default=True
        Whether to use a bias in the reservoir.
    trainable : bool, default=False
        Whether the reservoir weights are trainable.
    readout : str or type[ReadoutLayer], default="ridge"
        A built-in name (`"ridge"`, `"cholesky"`, `"cg"`, `"svd"`,
        `"pinv"`, `"incremental"`, `"rls"`, `"fista"`, `"lsmr"`) or a
        `resdag.layers.readouts.ReadoutLayer` subclass. Additional
        solver options go in `readout_kwargs`.
    readout_alpha : float, default=1e-6
        Ridge regularization for the readout.
    readout_bias : bool, default=True
        Whether to use a bias in the readout.
    readout_name : str, default="output"
        Name for the readout layer (used as the target key in training).
    readout_kwargs : dict, optional
        Extra readout options, such as `trainable=True`, `solver`,
        `state_noise` or `gram_dtype`. Architecture dimensions are fixed.
    **reservoir_kwargs : Any
        Additional keyword arguments forwarded to
        `resdag.layers.reservoirs.eusn.EuSNLayer` (e.g. `bias_scaling`,
        `seed`, `torchdiffeq_method`).

    Returns
    -------
    `resdag.core.ESNModel`
        Configured EuSN model ready for training and inference.

    Examples
    --------
    >>> from resdag.models import eusn
    >>> model = eusn(
    ...     reservoir_size=500, feedback_size=3, output_size=3,
    ...     epsilon=0.01, gamma=0.01,
    ... )

    See Also
    --------
    resdag.models.es2n : Edge-of-Stability State Network (discrete orthogonal skip).
    resdag.models.classic_esn : Traditional leaky ESN.
    resdag.layers.reservoirs.eusn.EuSNLayer : The reservoir layer.
    """
    return _esn_builder(
        reservoir_size=reservoir_size,
        feedback_size=feedback_size,
        output_size=output_size,
        augment=None,
        concat_input=True,
        input_size=input_size,
        input_initializer=input_initializer,
        reservoir_cls=EuSNLayer,
        topology=topology,
        spectral_radius=spectral_radius,
        feedback_initializer=feedback_initializer,
        activation=activation,
        bias=bias,
        trainable=trainable,
        readout=readout,
        readout_alpha=readout_alpha,
        readout_bias=readout_bias,
        readout_name=readout_name,
        readout_kwargs=readout_kwargs,
        epsilon=epsilon,
        gamma=gamma,
        substeps=substeps,
        solver=solver,
        **reservoir_kwargs,
    )

gated_esn

gated_esn(
    reservoir_size: int,
    feedback_size: int,
    output_size: int,
    input_size: int | None = None,
    input_initializer: InitializerSpec | None = None,
    topology: TopologySpec | None = None,
    spectral_radius: float = 0.9,
    update_gate_bias: float = 2.0,
    activation: str = "relu",
    gate_activation: str = "sigmoid",
    feedback_initializer: InitializerSpec | None = None,
    bias: bool = True,
    trainable: bool = False,
    concat_input: bool = True,
    readout: ReadoutSpec = "ridge",
    readout_alpha: float = 1e-06,
    readout_bias: bool = True,
    readout_name: str = "output",
    readout_kwargs: dict[str, Any] | None = None,
    **reservoir_kwargs: Any
) -> ESNModel

Build a gated ("reservoir GRU") ESN model.

The reservoir is a frozen (or trainable) LiGRU-style gated recurrent cell. The raw input is concatenated with the reservoir output before the readout, following the classic-ESN wiring:

Input -> GatedReservoirLayer -> Concatenate(Input, Reservoir) -> Readout
PARAMETER DESCRIPTION
reservoir_size

Number of units in the reservoir.

TYPE: int

feedback_size

Number of feedback features (input dimension).

TYPE: int

output_size

Number of output features.

TYPE: int

input_size

Dimension of an optional driving (exogenous) input. When given, the model takes two inputs (feedback, driver); the driver feeds the reservoir but is kept out of the input concatenation, so the readout in_features stays feedback_size + reservoir_size.

TYPE: int or None DEFAULT: None

input_initializer

Initializer for the driving-input weights. Only used when input_size is given.

TYPE: InitializerSpec DEFAULT: None

topology

Topology for the recurrent candidate weight. The update-gate recurrent weight is always dense-random.

TYPE: TopologySpec DEFAULT: None

spectral_radius

Desired spectral radius for the recurrent candidate weight.

TYPE: float DEFAULT: 0.9

update_gate_bias

Retention bias on the update gate (keeps a frozen gated reservoir from washing out its memory). See resdag.layers.cells.gated_cell.GatedReservoirCell.

TYPE: float DEFAULT: 2.0

activation

Candidate nonlinearity (LiGRU default is "relu").

TYPE: str DEFAULT: "relu"

gate_activation

Update-gate nonlinearity.

TYPE: str DEFAULT: "sigmoid"

feedback_initializer

Initializer for feedback weights.

TYPE: InitializerSpec DEFAULT: None

bias

Whether to use gate biases in the reservoir.

TYPE: bool DEFAULT: True

trainable

Whether reservoir weights are trainable. A frozen gated reservoir often underperforms an ESN; True (BPTT through the gates) is frequently the more useful setting. Note the ReLU candidate is unbounded, so a frozen autoregressive forecast that drifts off the attractor can grow large in magnitude (not merely track poorly) — prefer trainable=True for closed-loop forecasting.

TYPE: bool DEFAULT: False

concat_input

Whether to concatenate the raw input with the reservoir output before the readout.

TYPE: bool DEFAULT: True

readout

A built-in name ("ridge", "cholesky", "cg", "svd", "pinv", "incremental", "rls", "fista", "lsmr") or a resdag.layers.readouts.ReadoutLayer subclass. Additional solver options go in readout_kwargs.

TYPE: str or type[ReadoutLayer] DEFAULT: "ridge"

readout_alpha

Ridge regularization for the readout.

TYPE: float DEFAULT: 1e-6

readout_bias

Whether to use bias in the readout.

TYPE: bool DEFAULT: True

readout_name

Name for the readout layer (used as the target key in training).

TYPE: str DEFAULT: "output"

readout_kwargs

Extra readout options, such as trainable=True, solver, state_noise or gram_dtype. Architecture dimensions are fixed.

TYPE: dict DEFAULT: None

**reservoir_kwargs

Additional keyword arguments forwarded to resdag.layers.reservoirs.gated.GatedReservoirLayer.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION
`resdag.core.ESNModel`

Configured gated ESN model ready for training and inference.

RAISES DESCRIPTION
ValueError

If output_size is not a positive integer, or readout is an unknown string key.

TypeError

If readout is neither a known string key nor a resdag.layers.readouts.ReadoutLayer subclass.

Examples:

Trainable gated ESN on a 3-D signal:

>>> from resdag.models import gated_esn
>>> model = gated_esn(200, feedback_size=3, output_size=3, trainable=True)
See Also

resdag.models.classic_esn : The ungated classic ESN with the same wiring. resdag.layers.reservoirs.gated.GatedReservoirLayer : The gated reservoir layer.

Source code in src/resdag/models/gated_esn.py
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 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
 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
def gated_esn(
    reservoir_size: int,
    feedback_size: int,
    output_size: int,
    input_size: int | None = None,
    input_initializer: InitializerSpec | None = None,
    # Reservoir params
    topology: TopologySpec | None = None,
    spectral_radius: float = 0.9,
    update_gate_bias: float = 2.0,
    activation: str = "relu",
    gate_activation: str = "sigmoid",
    feedback_initializer: InitializerSpec | None = None,
    bias: bool = True,
    trainable: bool = False,
    concat_input: bool = True,
    # Readout params
    readout: ReadoutSpec = "ridge",
    readout_alpha: float = 1e-6,
    readout_bias: bool = True,
    readout_name: str = "output",
    readout_kwargs: dict[str, Any] | None = None,
    # Extra reservoir kwargs
    **reservoir_kwargs: Any,
) -> ESNModel:
    """Build a gated ("reservoir GRU") ESN model.

    The reservoir is a frozen (or trainable) LiGRU-style gated recurrent cell.
    The raw input is concatenated with the reservoir output before the readout,
    following the classic-ESN wiring:

    ```text
    Input -> GatedReservoirLayer -> Concatenate(Input, Reservoir) -> Readout
    ```

    Parameters
    ----------
    reservoir_size : int
        Number of units in the reservoir.
    feedback_size : int
        Number of feedback features (input dimension).
    output_size : int
        Number of output features.
    input_size : int or None, optional
        Dimension of an optional driving (exogenous) input.  When given, the
        model takes two inputs `(feedback, driver)`; the driver feeds the
        reservoir but is kept out of the input concatenation, so the readout
        `in_features` stays `feedback_size + reservoir_size`.
    input_initializer : InitializerSpec, optional
        Initializer for the driving-input weights.  Only used when `input_size`
        is given.
    topology : TopologySpec, optional
        Topology for the recurrent **candidate** weight.  The update-gate
        recurrent weight is always dense-random.
    spectral_radius : float, default=0.9
        Desired spectral radius for the recurrent candidate weight.
    update_gate_bias : float, default=2.0
        Retention bias on the update gate (keeps a frozen gated reservoir from
        washing out its memory).  See
        `resdag.layers.cells.gated_cell.GatedReservoirCell`.
    activation : str, default="relu"
        Candidate nonlinearity (LiGRU default is `"relu"`).
    gate_activation : str, default="sigmoid"
        Update-gate nonlinearity.
    feedback_initializer : InitializerSpec, optional
        Initializer for feedback weights.
    bias : bool, default=True
        Whether to use gate biases in the reservoir.
    trainable : bool, default=False
        Whether reservoir weights are trainable.  A frozen gated reservoir often
        underperforms an ESN; `True` (BPTT through the gates) is frequently the
        more useful setting.  Note the ReLU candidate is unbounded, so a *frozen*
        autoregressive forecast that drifts off the attractor can grow large in
        magnitude (not merely track poorly) — prefer `trainable=True` for
        closed-loop forecasting.
    concat_input : bool, default=True
        Whether to concatenate the raw input with the reservoir output before the
        readout.
    readout : str or type[ReadoutLayer], default="ridge"
        A built-in name (`"ridge"`, `"cholesky"`, `"cg"`, `"svd"`,
        `"pinv"`, `"incremental"`, `"rls"`, `"fista"`, `"lsmr"`) or a
        `resdag.layers.readouts.ReadoutLayer` subclass. Additional
        solver options go in `readout_kwargs`.
    readout_alpha : float, default=1e-6
        Ridge regularization for the readout.
    readout_bias : bool, default=True
        Whether to use bias in the readout.
    readout_name : str, default="output"
        Name for the readout layer (used as the target key in training).
    readout_kwargs : dict, optional
        Extra readout options, such as `trainable=True`, `solver`,
        `state_noise` or `gram_dtype`. Architecture dimensions are fixed.
    **reservoir_kwargs : Any
        Additional keyword arguments forwarded to
        `resdag.layers.reservoirs.gated.GatedReservoirLayer`.

    Returns
    -------
    `resdag.core.ESNModel`
        Configured gated ESN model ready for training and inference.

    Raises
    ------
    ValueError
        If `output_size` is not a positive integer, or `readout` is an
        unknown string key.
    TypeError
        If `readout` is neither a known string key nor a
        `resdag.layers.readouts.ReadoutLayer` subclass.

    Examples
    --------
    Trainable gated ESN on a 3-D signal:

    >>> from resdag.models import gated_esn
    >>> model = gated_esn(200, feedback_size=3, output_size=3, trainable=True)

    See Also
    --------
    resdag.models.classic_esn : The ungated classic ESN with the same wiring.
    resdag.layers.reservoirs.gated.GatedReservoirLayer : The gated reservoir layer.
    """
    if output_size <= 0:
        raise ValueError(f"output_size must be a positive integer, got {output_size!r}")

    # Resolve the readout up front so an invalid spec fails before construction.

    inp = reservoir_input(
        feedback_size, dtype=reservoir_kwargs.get("dtype"), device=reservoir_kwargs.get("device")
    )
    driver = (
        reservoir_input(
            input_size, dtype=reservoir_kwargs.get("dtype"), device=reservoir_kwargs.get("device")
        )
        if input_size
        else None
    )

    reservoir = GatedReservoirLayer(
        reservoir_size=reservoir_size,
        feedback_size=feedback_size,
        input_size=input_size,
        topology=topology,
        spectral_radius=spectral_radius,
        update_gate_bias=update_gate_bias,
        activation=activation,
        gate_activation=gate_activation,
        feedback_initializer=feedback_initializer,
        input_initializer=input_initializer,
        bias=bias,
        trainable=trainable,
        **reservoir_kwargs,
    )

    output: SymbolicTensor = reservoir(inp) if driver is None else reservoir(inp, driver)
    model_inputs = inp if driver is None else [inp, driver]

    if concat_input:
        output = Concatenate()(inp, output)
        readout_in_features = feedback_size + reservoir_size
    else:
        readout_in_features = reservoir_size

    readout_layer = _make_readout(
        readout,
        in_features=readout_in_features,
        out_features=output_size,
        bias=readout_bias,
        alpha=readout_alpha,
        name=readout_name,
        readout_kwargs=readout_kwargs,
    ).to(device=reservoir.weight_feedback.device, dtype=reservoir.weight_feedback.dtype)(output)

    return ESNModel(model_inputs, readout_layer)

headless_esn

headless_esn(
    reservoir_size: int,
    feedback_size: int,
    topology: TopologySpec | None = None,
    spectral_radius: float = 0.9,
    leak_rate: float = 1.0,
    feedback_initializer: InitializerSpec | None = None,
    activation: str = "tanh",
    bias: bool = True,
    trainable: bool = False,
    **reservoir_kwargs: Any
) -> ESNModel

Build an ESN model with no readout layer.

This model can be used to study the dynamics of the reservoir by applying different transformations to the reservoir states without a readout layer. Useful for analyzing reservoir dynamics, state space properties, and feature extraction.

Architecture: Input -> Reservoir (output)

The reservoir is not connected to a readout layer, allowing direct access to reservoir states for analysis or custom processing.

PARAMETER DESCRIPTION
reservoir_size

Number of units in the reservoir.

TYPE: int

feedback_size

Number of feedback features.

TYPE: int

topology

Topology for recurrent weights. Accepts: - str: Registry name (e.g., "erdos_renyi") - tuple: (name, params) like ("watts_strogatz", {"k": 6, "p": 0.1}) - GraphTopology: Pre-configured object

TYPE: TopologySpec DEFAULT: None

spectral_radius

Desired spectral radius for recurrent weights.

TYPE: float DEFAULT: 0.9

leak_rate

Leaky integration rate (1.0 = no leak).

TYPE: float DEFAULT: 1.0

feedback_initializer

Initializer for feedback weights.

TYPE: InitializerSpec DEFAULT: None

activation

Activation function ("tanh", "relu", "sigmoid", "identity").

TYPE: str DEFAULT: "tanh"

bias

Whether to use bias in the reservoir.

TYPE: bool DEFAULT: True

trainable

Whether reservoir weights are trainable.

TYPE: bool DEFAULT: False

**reservoir_kwargs

Additional keyword arguments passed to ESNLayer.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION
ESNModel

ESN model with reservoir output only.

Examples:

>>> from resdag.models import headless_esn
>>> model = headless_esn(100, 1)
>>> reservoir_states = model(input_data)  # Direct reservoir output
Source code in src/resdag/models/headless_esn.py
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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
def headless_esn(
    reservoir_size: int,
    feedback_size: int,
    # Reservoir params
    topology: TopologySpec | None = None,
    spectral_radius: float = 0.9,
    leak_rate: float = 1.0,
    feedback_initializer: InitializerSpec | None = None,
    activation: str = "tanh",
    bias: bool = True,
    trainable: bool = False,
    # Extra reservoir kwargs
    **reservoir_kwargs: Any,
) -> ESNModel:
    """Build an ESN model with no readout layer.

    This model can be used to study the dynamics of the reservoir by applying
    different transformations to the reservoir states without a readout layer.
    Useful for analyzing reservoir dynamics, state space properties, and
    feature extraction.

    Architecture:
        Input -> Reservoir (output)

    The reservoir is not connected to a readout layer, allowing direct
    access to reservoir states for analysis or custom processing.

    Parameters
    ----------
    reservoir_size : int
        Number of units in the reservoir.
    feedback_size : int
        Number of feedback features.
    topology : TopologySpec, optional
        Topology for recurrent weights. Accepts:
        - str: Registry name (e.g., "erdos_renyi")
        - tuple: (name, params) like ("watts_strogatz", {"k": 6, "p": 0.1})
        - GraphTopology: Pre-configured object
    spectral_radius : float, default=0.9
        Desired spectral radius for recurrent weights.
    leak_rate : float, default=1.0
        Leaky integration rate (1.0 = no leak).
    feedback_initializer : InitializerSpec, optional
        Initializer for feedback weights.
    activation : str, default="tanh"
        Activation function ("tanh", "relu", "sigmoid", "identity").
    bias : bool, default=True
        Whether to use bias in the reservoir.
    trainable : bool, default=False
        Whether reservoir weights are trainable.
    **reservoir_kwargs
        Additional keyword arguments passed to ESNLayer.

    Returns
    -------
    ESNModel
        ESN model with reservoir output only.

    Examples
    --------
    >>> from resdag.models import headless_esn
    >>> model = headless_esn(100, 1)
    >>> reservoir_states = model(input_data)  # Direct reservoir output
    """
    # Headless: reservoir output only, no augmentation and no readout.
    return _esn_builder(
        reservoir_size=reservoir_size,
        feedback_size=feedback_size,
        output_size=None,
        augment=None,
        topology=topology,
        spectral_radius=spectral_radius,
        leak_rate=leak_rate,
        feedback_initializer=feedback_initializer,
        activation=activation,
        bias=bias,
        trainable=trainable,
        **reservoir_kwargs,
    )

KnowledgeModel

KnowledgeModel(fn: KnowledgeFn | Module, model_out_size: int)

Bases: Module

Wrap a knowledge-based expert f(u) -> u_next as a DAG layer.

Adapts an arbitrary one-step-ahead predictor — a plain callable or another torch.nn.Module (e.g. one Euler/RK step of an approximate ODE) — so it slots into a pytorch_symbolic model and is re-evaluated on the current feedback at every timestep, including the autoregressive forecast loop where the reservoir feeds the model its own previous prediction.

The wrapped callable is applied directly to the (batch, time, features) (or single-step (batch, 1, features)) tensor and must broadcast over the leading batch/time axes, operating feature-wise on the last dimension — the standard PyTorch idiom. Its output feature dimension, model_out_size, may differ from the input dimension (though it is typically equal, since the expert predicts the next state).

PARAMETER DESCRIPTION
fn

The knowledge model. Called as fn(u) with u of shape (batch, time, features) and must return a tensor of shape (batch, time, model_out_size) — i.e. it may change only the last (feature) dimension. A crude approximate integrator is enough; it does not need to be accurate, only informative.

TYPE: callable or Module

model_out_size

Feature dimension of fn's output. Used by hybrid_esn to size the concatenations and the informed input split; validated at call time.

TYPE: int

ATTRIBUTE DESCRIPTION
fn

The wrapped knowledge model. Registered as a submodule when it is an torch.nn.Module, so its parameters/buffers move with .to().

TYPE: callable or Module

model_out_size

The declared output feature dimension.

TYPE: int

RAISES DESCRIPTION
ValueError

At forward time, if fn's output rank does not match its input or its last dimension is not model_out_size.

Examples:

A rough Lorenz-63 Euler step used as a physics prior::

>>> import torch
>>> from resdag.models import KnowledgeModel
>>> def lorenz_euler(u, dt=0.02, sigma=10.0, rho=28.0, beta=8.0 / 3.0):
...     x, y, z = u[..., 0], u[..., 1], u[..., 2]
...     dx = sigma * (y - x)
...     dy = x * (rho - z) - y
...     dz = x * y - beta * z
...     return u + dt * torch.stack([dx, dy, dz], dim=-1)
>>> expert = KnowledgeModel(lorenz_euler, model_out_size=3)
>>> u = torch.randn(4, 50, 3)
>>> expert(u).shape
torch.Size([4, 50, 3])
See Also

hybrid_esn : The factory that wires this expert into a hybrid ESN.

RAISES DESCRIPTION
TypeError

If fn is not callable.

ValueError

If model_out_size is not a positive integer.

Source code in src/resdag/models/hybrid_esn.py
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
def __init__(self, fn: KnowledgeFn | nn.Module, model_out_size: int) -> None:
    """Store the callable and its declared output dimension.

    Raises
    ------
    TypeError
        If `fn` is not callable.
    ValueError
        If `model_out_size` is not a positive integer.
    """
    super().__init__()
    if not callable(fn):
        raise TypeError(f"KnowledgeModel: fn must be callable, got {type(fn).__name__}.")
    if not isinstance(model_out_size, int) or model_out_size <= 0:
        raise ValueError(
            f"KnowledgeModel: model_out_size must be a positive integer, "
            f"got {model_out_size!r}."
        )
    # Registering an nn.Module submodule under ``fn`` means its parameters and
    # buffers are discovered by ``.parameters()`` / moved by ``.to(...)``. A
    # plain callable is stored as a bare attribute (no parameters to track).
    self.fn = fn
    self.model_out_size = model_out_size

forward

forward(u: Tensor) -> Tensor

Apply the knowledge model to the current state u.

PARAMETER DESCRIPTION
u

Current state of shape (batch, time, features) (or the single-step (batch, 1, features) slice used during autoregressive forecasting).

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The one-step-ahead prediction of shape (batch, time, model_out_size).

RAISES DESCRIPTION
ValueError

If the wrapped model's output rank differs from u or its last dimension is not model_out_size.

Source code in src/resdag/models/hybrid_esn.py
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
def forward(self, u: torch.Tensor) -> torch.Tensor:
    """Apply the knowledge model to the current state `u`.

    Parameters
    ----------
    u : torch.Tensor
        Current state of shape `(batch, time, features)` (or the single-step
        `(batch, 1, features)` slice used during autoregressive forecasting).

    Returns
    -------
    torch.Tensor
        The one-step-ahead prediction of shape
        `(batch, time, model_out_size)`.

    Raises
    ------
    ValueError
        If the wrapped model's output rank differs from `u` or its last
        dimension is not `model_out_size`.
    """
    out = self.fn(u)
    if out.shape[:-1] != u.shape[:-1] or out.shape[-1] != self.model_out_size:
        raise ValueError(
            f"KnowledgeModel: fn(u) must return shape "
            f"{(*u.shape[:-1], self.model_out_size)} (same batch/time as the "
            f"input, last dim = model_out_size={self.model_out_size}); got "
            f"{tuple(out.shape)} for input {tuple(u.shape)}."
        )
    return out

hybrid_esn

hybrid_esn(
    knowledge_model: KnowledgeModel | KnowledgeFn | Module,
    reservoir_size: int,
    feedback_size: int,
    output_size: int,
    *,
    model_out_size: int | None = None,
    gamma: float = 0.5,
    input_scaling: float = 0.1,
    topology: TopologySpec | None = None,
    spectral_radius: float = 0.9,
    leak_rate: float = 1.0,
    activation: str = "tanh",
    bias: bool = True,
    trainable: bool = False,
    readout: ReadoutSpec = "ridge",
    readout_alpha: float = 1e-06,
    readout_bias: bool = True,
    readout_name: str = "output",
    readout_kwargs: dict[str, Any] | None = None,
    **reservoir_kwargs: Any
) -> ESNModel

Build a hybrid physics-prior ESN (Pathak et al. 2018).

Combines a reservoir with an imperfect knowledge-based expert K. The expert's one-step-ahead prediction K(u) is concatenated with the raw input to drive the reservoir, and concatenated with the reservoir state before the readout, so the reservoir only has to learn the residual the expert gets wrong.

Architecture:

             +---------------- K(u) --------------------+
             |                                          |
Input -- u --+--> Concatenate([u, K(u)]) --> Reservoir  |
                                                 |       v
                                                 +--> Concatenate([h, K(u)]) --> Readout

The reservoir's input weights use the informed split (resdag.init.input_feedback.InformedInputInitializer): a fraction gamma of the units are wired to the raw-state block u and 1 - gamma to the knowledge-model block K(u).

PARAMETER DESCRIPTION
knowledge_model

The knowledge-based expert. A bare callable / torch.nn.Module f(u) -> u_next is wrapped in a KnowledgeModel automatically (using model_out_size, defaulting to feedback_size); pass a pre-built KnowledgeModel to control its declared output size.

TYPE: KnowledgeModel, callable, or torch.nn.Module

reservoir_size

Number of units in the reservoir.

TYPE: int

feedback_size

Number of feedback features (the input dimension of the model, u).

TYPE: int

output_size

Number of output features. For autoregressive forecast this must equal feedback_size (the first model output is fed back as u).

TYPE: int

model_out_size

Feature dimension of the knowledge model's output. Only used when knowledge_model is a bare callable (to build the wrapper); ignored when a KnowledgeModel is passed (its own model_out_size is used). Defaults to feedback_size (the usual case: the expert predicts the next full state).

TYPE: int or None DEFAULT: None

gamma

Fraction of reservoir units wired to the raw-state block u by the informed input split; 1 - gamma are wired to the K(u) block. Must lie in [0, 1]. gamma near 1 weights the reservoir toward the raw state, near 0 toward the knowledge model.

TYPE: float DEFAULT: 0.5

input_scaling

Half-width of the informed input weights: each nonzero entry is drawn uniformly from [-input_scaling, input_scaling].

TYPE: float DEFAULT: 0.1

topology

Topology for the recurrent weights. Accepts a registry name, a (name, params) tuple, a callable, or a configured resdag.init.topology.TopologyInitializer.

TYPE: TopologySpec DEFAULT: None

spectral_radius

Target spectral radius for the recurrent weights.

TYPE: float DEFAULT: 0.9

leak_rate

Leaky-integration rate (1.0 = no leak).

TYPE: float DEFAULT: 1.0

activation

Activation function ("tanh", "relu", "sigmoid", "identity").

TYPE: str DEFAULT: "tanh"

bias

Whether the reservoir uses a bias term.

TYPE: bool DEFAULT: True

trainable

Whether the reservoir weights are trainable.

TYPE: bool DEFAULT: False

readout

A built-in name ("ridge", "cholesky", "cg", "svd", "pinv", "incremental", "rls", "fista", "lsmr") or a resdag.layers.readouts.ReadoutLayer subclass. Additional solver options go in readout_kwargs.

TYPE: str or type[ReadoutLayer] DEFAULT: "ridge"

readout_alpha

Ridge regression regularization for the readout.

TYPE: float DEFAULT: 1e-6

readout_bias

Whether the readout uses a bias term.

TYPE: bool DEFAULT: True

readout_name

Name for the readout layer (used as the target key in training).

TYPE: str DEFAULT: "output"

readout_kwargs

Extra readout options, such as trainable=True, solver, state_noise or gram_dtype. Architecture dimensions are fixed.

TYPE: dict DEFAULT: None

**reservoir_kwargs

Additional keyword arguments forwarded to resdag.layers.ESNLayer.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION
`resdag.core.ESNModel`

The assembled hybrid ESN, ready for training and forecasting.

RAISES DESCRIPTION
ValueError

If output_size is not a positive integer, or (via the informed initializer) if the wiring dimensions are inconsistent.

Notes

The reservoir's feedback_size is feedback_size + model_out_size because it consumes the concatenation [u, K(u)]; the model's input dimension stays feedback_size (K(u) is computed inside the graph). The readout in_features is reservoir_size + model_out_size (it sees [h, K(u)]). During autoregressive forecast, only the readout output is fed back as the next u; K is re-evaluated on it every step, so the physics prior stays live throughout the rollout.

Examples:

A rough Lorenz Euler step as the physics prior::

>>> import torch
>>> from resdag.models import hybrid_esn
>>> def lorenz_euler(u, dt=0.02, sigma=10.0, rho=28.0, beta=8.0 / 3.0):
...     x, y, z = u[..., 0], u[..., 1], u[..., 2]
...     dx = sigma * (y - x)
...     dy = x * (rho - z) - y
...     dz = x * y - beta * z
...     return u + dt * torch.stack([dx, dy, dz], dim=-1)
>>> model = hybrid_esn(
...     lorenz_euler,
...     reservoir_size=400,
...     feedback_size=3,
...     output_size=3,
...     gamma=0.5,
... )

Training and forecasting are identical to any other premade model::

>>> from resdag.training import ESNTrainer
>>> trainer = ESNTrainer(model)
>>> trainer.fit(
...     warmup_inputs=(warmup,),
...     train_inputs=(train,),
...     targets={"output": target},
... )
>>> predictions = model.forecast(warmup, horizon=500)
See Also

KnowledgeModel : The expert wrapper used here. resdag.init.input_feedback.InformedInputInitializer : The informed input split. deep_esn : Stacked (hierarchical) reservoirs.

Source code in src/resdag/models/hybrid_esn.py
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
def hybrid_esn(
    knowledge_model: KnowledgeModel | KnowledgeFn | nn.Module,
    reservoir_size: int,
    feedback_size: int,
    output_size: int,
    *,
    model_out_size: int | None = None,
    gamma: float = 0.5,
    input_scaling: float = 0.1,
    # Reservoir params
    topology: TopologySpec | None = None,
    spectral_radius: float = 0.9,
    leak_rate: float = 1.0,
    activation: str = "tanh",
    bias: bool = True,
    trainable: bool = False,
    # Readout params
    readout: ReadoutSpec = "ridge",
    readout_alpha: float = 1e-6,
    readout_bias: bool = True,
    readout_name: str = "output",
    readout_kwargs: dict[str, Any] | None = None,
    # Extra reservoir kwargs
    **reservoir_kwargs: Any,
) -> ESNModel:
    """Build a hybrid physics-prior ESN (Pathak et al. 2018).

    Combines a reservoir with an imperfect knowledge-based expert `K`.  The
    expert's one-step-ahead prediction `K(u)` is concatenated with the raw
    input to drive the reservoir, **and** concatenated with the reservoir state
    before the readout, so the reservoir only has to learn the residual the
    expert gets wrong.

    Architecture:

    ```text
                 +---------------- K(u) --------------------+
                 |                                          |
    Input -- u --+--> Concatenate([u, K(u)]) --> Reservoir  |
                                                     |       v
                                                     +--> Concatenate([h, K(u)]) --> Readout
    ```

    The reservoir's input weights use the informed split
    (`resdag.init.input_feedback.InformedInputInitializer`): a fraction
    `gamma` of the units are wired to the raw-state block `u` and `1 - gamma`
    to the knowledge-model block `K(u)`.

    Parameters
    ----------
    knowledge_model : KnowledgeModel, callable, or torch.nn.Module
        The knowledge-based expert.  A bare callable / `torch.nn.Module`
        `f(u) -> u_next` is wrapped in a `KnowledgeModel` automatically
        (using `model_out_size`, defaulting to `feedback_size`); pass a
        pre-built `KnowledgeModel` to control its declared output size.
    reservoir_size : int
        Number of units in the reservoir.
    feedback_size : int
        Number of feedback features (the input dimension of the model, `u`).
    output_size : int
        Number of output features.  For autoregressive `forecast` this must
        equal `feedback_size` (the first model output is fed back as `u`).
    model_out_size : int or None, optional
        Feature dimension of the knowledge model's output.  Only used when
        `knowledge_model` is a bare callable (to build the wrapper); ignored when
        a `KnowledgeModel` is passed (its own `model_out_size` is used).
        Defaults to `feedback_size` (the usual case: the expert predicts the
        next full state).
    gamma : float, default=0.5
        Fraction of reservoir units wired to the raw-state block `u` by the
        informed input split; `1 - gamma` are wired to the `K(u)` block.  Must
        lie in `[0, 1]`.  `gamma` near `1` weights the reservoir toward the
        raw state, near `0` toward the knowledge model.
    input_scaling : float, default=0.1
        Half-width of the informed input weights: each nonzero entry is drawn
        uniformly from `[-input_scaling, input_scaling]`.
    topology : TopologySpec, optional
        Topology for the recurrent weights.  Accepts a registry name, a
        `(name, params)` tuple, a callable, or a configured
        `resdag.init.topology.TopologyInitializer`.
    spectral_radius : float, default=0.9
        Target spectral radius for the recurrent weights.
    leak_rate : float, default=1.0
        Leaky-integration rate (1.0 = no leak).
    activation : str, default="tanh"
        Activation function (`"tanh"`, `"relu"`, `"sigmoid"`,
        `"identity"`).
    bias : bool, default=True
        Whether the reservoir uses a bias term.
    trainable : bool, default=False
        Whether the reservoir weights are trainable.
    readout : str or type[ReadoutLayer], default="ridge"
        A built-in name (`"ridge"`, `"cholesky"`, `"cg"`, `"svd"`,
        `"pinv"`, `"incremental"`, `"rls"`, `"fista"`, `"lsmr"`) or a
        `resdag.layers.readouts.ReadoutLayer` subclass. Additional
        solver options go in `readout_kwargs`.
    readout_alpha : float, default=1e-6
        Ridge regression regularization for the readout.
    readout_bias : bool, default=True
        Whether the readout uses a bias term.
    readout_name : str, default="output"
        Name for the readout layer (used as the target key in training).
    readout_kwargs : dict, optional
        Extra readout options, such as `trainable=True`, `solver`,
        `state_noise` or `gram_dtype`. Architecture dimensions are fixed.
    **reservoir_kwargs : Any
        Additional keyword arguments forwarded to `resdag.layers.ESNLayer`.

    Returns
    -------
    `resdag.core.ESNModel`
        The assembled hybrid ESN, ready for training and forecasting.

    Raises
    ------
    ValueError
        If `output_size` is not a positive integer, or (via the informed
        initializer) if the wiring dimensions are inconsistent.

    Notes
    -----
    The reservoir's `feedback_size` is `feedback_size + model_out_size`
    because it consumes the concatenation `[u, K(u)]`; the *model's* input
    dimension stays `feedback_size` (`K(u)` is computed inside the graph).
    The readout `in_features` is `reservoir_size + model_out_size` (it sees
    `[h, K(u)]`).  During autoregressive `forecast`, only the readout
    output is fed back as the next `u`; `K` is re-evaluated on it every step,
    so the physics prior stays live throughout the rollout.

    Examples
    --------
    A rough Lorenz Euler step as the physics prior::

    >>> import torch
    >>> from resdag.models import hybrid_esn
    >>> def lorenz_euler(u, dt=0.02, sigma=10.0, rho=28.0, beta=8.0 / 3.0):
    ...     x, y, z = u[..., 0], u[..., 1], u[..., 2]
    ...     dx = sigma * (y - x)
    ...     dy = x * (rho - z) - y
    ...     dz = x * y - beta * z
    ...     return u + dt * torch.stack([dx, dy, dz], dim=-1)
    >>> model = hybrid_esn(
    ...     lorenz_euler,
    ...     reservoir_size=400,
    ...     feedback_size=3,
    ...     output_size=3,
    ...     gamma=0.5,
    ... )

    Training and forecasting are identical to any other premade model::

    >>> from resdag.training import ESNTrainer
    >>> trainer = ESNTrainer(model)
    >>> trainer.fit(
    ...     warmup_inputs=(warmup,),
    ...     train_inputs=(train,),
    ...     targets={"output": target},
    ... )
    >>> predictions = model.forecast(warmup, horizon=500)

    See Also
    --------
    KnowledgeModel : The expert wrapper used here.
    resdag.init.input_feedback.InformedInputInitializer : The informed input split.
    deep_esn : Stacked (hierarchical) reservoirs.
    """
    if not isinstance(output_size, int) or output_size <= 0:
        raise ValueError(
            f"hybrid_esn: output_size must be a positive integer, got {output_size!r}."
        )

    # Wrap a bare callable/Module in a KnowledgeModel; a pre-built one is used
    # as-is (its own model_out_size wins). The expert predicts the next state, so
    # model_out_size defaults to feedback_size.
    if isinstance(knowledge_model, KnowledgeModel):
        expert = knowledge_model
    else:
        expert = KnowledgeModel(
            knowledge_model,
            model_out_size=model_out_size if model_out_size is not None else feedback_size,
        )
    model_out = expert.model_out_size
    expert.to(device=reservoir_kwargs.get("device"), dtype=reservoir_kwargs.get("dtype"))

    # Resolve the readout spec up front so an invalid one fails before any
    # partial construction.

    # The model input u has dimension feedback_size; K(u) is computed in-graph, so
    # it is re-evaluated on the model's own output each autoregressive step.
    inp = reservoir_input(
        feedback_size, dtype=reservoir_kwargs.get("dtype"), device=reservoir_kwargs.get("device")
    )
    k = expert(inp)  # (batch, time, model_out)

    # Pre-reservoir: drive the reservoir with [u, K(u)].
    reservoir_in = Concatenate()(inp, k)
    reservoir_feedback_size = feedback_size + model_out

    # Informed input split: the first ``feedback_size`` columns are the raw-state
    # block, the trailing ``model_out`` columns the knowledge-model block. gamma is
    # the fraction of units wired to the state block.
    feedback_initializer = (
        "informed_init",
        {"model_in_size": model_out, "gamma": gamma, "input_scaling": input_scaling},
    )

    reservoir_state = ESNLayer(
        reservoir_size=reservoir_size,
        feedback_size=reservoir_feedback_size,
        topology=topology,
        spectral_radius=spectral_radius,
        leak_rate=leak_rate,
        feedback_initializer=feedback_initializer,
        activation=activation,
        bias=bias,
        trainable=trainable,
        **reservoir_kwargs,
    )(reservoir_in)

    # Pre-readout: the readout sees [h, K(u)].
    readout_in = Concatenate()(reservoir_state, k)
    readout_in_features = reservoir_size + model_out

    readout_layer = _make_readout(
        readout,
        in_features=readout_in_features,
        out_features=output_size,
        bias=readout_bias,
        alpha=readout_alpha,
        name=readout_name,
        readout_kwargs=readout_kwargs,
    ).to(device=reservoir_kwargs.get("device"), dtype=reservoir_kwargs.get("dtype"))(readout_in)

    return ESNModel(inp, readout_layer)

linear_esn

linear_esn(
    reservoir_size: int,
    feedback_size: int,
    topology: TopologySpec | None = None,
    spectral_radius: float = 0.9,
    leak_rate: float = 1.0,
    feedback_initializer: InitializerSpec | None = None,
    bias: bool = True,
    trainable: bool = False,
    **reservoir_kwargs: Any
) -> ESNModel

Build an ESN model with no readout layer and a linear activation function.

This model uses a linear activation function in the reservoir, which can be useful for studying linear dynamics or as a baseline for comparison with nonlinear reservoirs.

Architecture: Input -> Reservoir(activation='identity') (output)

PARAMETER DESCRIPTION
reservoir_size

Number of units in the reservoir.

TYPE: int

feedback_size

Number of feedback features.

TYPE: int

topology

Topology for recurrent weights. Accepts: - str: Registry name (e.g., "erdos_renyi") - tuple: (name, params) like ("watts_strogatz", {"k": 6, "p": 0.1}) - GraphTopology: Pre-configured object

TYPE: TopologySpec DEFAULT: None

spectral_radius

Desired spectral radius for recurrent weights.

TYPE: float DEFAULT: 0.9

leak_rate

Leaky integration rate (1.0 = no leak).

TYPE: float DEFAULT: 1.0

feedback_initializer

Initializer for feedback weights.

TYPE: InitializerSpec DEFAULT: None

bias

Whether to use bias in the reservoir.

TYPE: bool DEFAULT: True

trainable

Whether reservoir weights are trainable.

TYPE: bool DEFAULT: False

**reservoir_kwargs

Additional keyword arguments passed to ESNLayer. activation is not accepted here: linear_esn forces activation="identity" by design.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION
ESNModel

ESN model with linear reservoir activation.

RAISES DESCRIPTION
ValueError

If activation is passed via reservoir_kwargs. linear_esn forces a linear (identity) activation by design, so overriding it is not allowed.

Examples:

>>> from resdag.models import linear_esn
>>> model = linear_esn(100, 1)
>>> linear_states = model(input_data)
Source code in src/resdag/models/linear_esn.py
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 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
 94
 95
 96
 97
 98
 99
100
def linear_esn(
    reservoir_size: int,
    feedback_size: int,
    # Reservoir params
    topology: TopologySpec | None = None,
    spectral_radius: float = 0.9,
    leak_rate: float = 1.0,
    feedback_initializer: InitializerSpec | None = None,
    bias: bool = True,
    trainable: bool = False,
    # Extra reservoir kwargs
    **reservoir_kwargs: Any,
) -> ESNModel:
    """Build an ESN model with no readout layer and a linear activation function.

    This model uses a linear activation function in the reservoir, which can be
    useful for studying linear dynamics or as a baseline for comparison with
    nonlinear reservoirs.

    Architecture:
        Input -> Reservoir(activation='identity') (output)

    Parameters
    ----------
    reservoir_size : int
        Number of units in the reservoir.
    feedback_size : int
        Number of feedback features.
    topology : TopologySpec, optional
        Topology for recurrent weights. Accepts:
        - str: Registry name (e.g., "erdos_renyi")
        - tuple: (name, params) like ("watts_strogatz", {"k": 6, "p": 0.1})
        - GraphTopology: Pre-configured object
    spectral_radius : float, default=0.9
        Desired spectral radius for recurrent weights.
    leak_rate : float, default=1.0
        Leaky integration rate (1.0 = no leak).
    feedback_initializer : InitializerSpec, optional
        Initializer for feedback weights.
    bias : bool, default=True
        Whether to use bias in the reservoir.
    trainable : bool, default=False
        Whether reservoir weights are trainable.
    **reservoir_kwargs
        Additional keyword arguments passed to ESNLayer.  `activation` is not
        accepted here: `linear_esn` forces `activation="identity"` by design.

    Returns
    -------
    ESNModel
        ESN model with linear reservoir activation.

    Raises
    ------
    ValueError
        If `activation` is passed via `reservoir_kwargs`.  `linear_esn`
        forces a linear (identity) activation by design, so overriding it is
        not allowed.

    Examples
    --------
    >>> from resdag.models import linear_esn
    >>> model = linear_esn(100, 1)
    >>> linear_states = model(input_data)
    """
    # Linear: reservoir output only, no readout, identity activation forced.
    # Forbid an explicit ``activation`` override rather than letting it collide
    # with the hardcoded ``activation="identity"`` below (which would otherwise
    # raise a cryptic "multiple values for keyword argument 'activation'").
    if "activation" in reservoir_kwargs:
        raise ValueError(
            "linear_esn forces activation='identity'; do not pass activation="
            f"{reservoir_kwargs['activation']!r}. Use a different premade model "
            "(e.g. headless_esn) for a nonlinear reservoir without a readout."
        )

    return _esn_builder(
        reservoir_size=reservoir_size,
        feedback_size=feedback_size,
        output_size=None,
        augment=None,
        topology=topology,
        spectral_radius=spectral_radius,
        leak_rate=leak_rate,
        feedback_initializer=feedback_initializer,
        activation="identity",  # Force linear activation
        bias=bias,
        trainable=trainable,
        **reservoir_kwargs,
    )

lsm

lsm(
    reservoir_size: int,
    feedback_size: int,
    output_size: int,
    input_size: int | None = None,
    input_initializer: InitializerSpec | None = None,
    tau_mem: float = 20.0,
    tau_syn: float = 10.0,
    dt: float = 1.0,
    synaptic_current: bool = False,
    v_threshold: float = 1.0,
    reset: str = "subtract",
    surrogate_beta: float = 10.0,
    trace_decay: float = 0.9,
    topology: TopologySpec | None = None,
    spectral_radius: float = 0.9,
    feedback_initializer: InitializerSpec | None = None,
    bias: bool = True,
    trainable: bool = False,
    concat_input: bool = True,
    readout: ReadoutSpec = "ridge",
    readout_alpha: float = 1e-06,
    readout_bias: bool = True,
    readout_name: str = "output",
    readout_kwargs: dict[str, Any] | None = None,
    **reservoir_kwargs: Any
) -> ESNModel

Build a spiking Liquid State Machine (LSM) model.

The reservoir is a recurrent network of leaky integrate-and-fire neurons (resdag.layers.reservoirs.lif.LIFReservoirLayer); its real-valued synaptic-trace output is concatenated with the raw input and read out by a ridge regression, following the classic-ESN wiring:

Input -> LIFReservoirLayer -> Concatenate(Input, trace) -> Readout

Important.

This is an input-driven reservoir (Maass 2002), not a closed-loop chaos forecaster — the reservoir output is a filtered spike trace, not the feedback variable, so it cannot autoregress on itself. Its use is driven regression / classification, where a readout maps the filtered liquid state to a target. For autoregressive chaotic forecasting use resdag.models.ott_esn, resdag.models.classic_esn, or resdag.models.es2n. Continuous inputs enter as injected current.

PARAMETER DESCRIPTION
reservoir_size

Number of spiking units in the liquid.

TYPE: int

feedback_size

Number of input features driving the reservoir.

TYPE: int

output_size

Number of output (target) features.

TYPE: int

input_size

Dimension of an optional second driving input. When given, the model takes two inputs (feedback, driver); the driver feeds the reservoir but is kept out of the input concatenation, so the readout in_features stays feedback_size + reservoir_size.

TYPE: int or None DEFAULT: None

input_initializer

Initializer for the driving-input weights. Only used when input_size is given.

TYPE: InitializerSpec DEFAULT: None

tau_mem

Membrane time constant \(\tau_\text{mem}\) (in units of dt). Sets the membrane decay \(\beta = e^{-\Delta t/\tau_\text{mem}}\) — longer values give longer fading memory.

TYPE: float DEFAULT: 20.0

tau_syn

Synaptic time constant \(\tau_\text{syn}\). Only used when synaptic_current=True (CuBa-LIF).

TYPE: float DEFAULT: 10.0

dt

Integration timestep \(\Delta t\).

TYPE: float DEFAULT: 1.0

synaptic_current

If True, use the second-order current-based LIF (CuBa-LIF), which adds an explicit synaptic-current state and smoother temporal filtering.

TYPE: bool DEFAULT: False

v_threshold

Firing threshold.

TYPE: float DEFAULT: 1.0

reset

Membrane reset on a spike (soft subtract vs hard zero).

TYPE: (subtract, zero) DEFAULT: 'subtract'

surrogate_beta

Fast-sigmoid surrogate slope for the straight-through spike gradient (only matters when trainable=True).

TYPE: float DEFAULT: 10.0

trace_decay

Decay \(\kappa\) of the low-pass readout trace \(r_t = \kappa r_{t-1} + s_t\) — the real-valued signal the readout regresses on.

TYPE: float DEFAULT: 0.9

topology

Topology for the recurrent spike-coupling weight W_rec. Accepts a registry name, a (name, params) tuple, a callable, or a configured resdag.init.topology.TopologyInitializer.

TYPE: TopologySpec DEFAULT: None

spectral_radius

Target spectral radius for W_rec (recurrent spike-coupling strength).

TYPE: float DEFAULT: 0.9

feedback_initializer

Initializer for the feedback weights.

TYPE: InitializerSpec DEFAULT: None

bias

Whether to use a bias current in the reservoir.

TYPE: bool DEFAULT: True

trainable

Whether the reservoir weights are trainable (via the surrogate spike gradient). A frozen liquid + fitted readout is the classic LSM; set True to fine-tune the liquid with SGD.

TYPE: bool DEFAULT: False

concat_input

Whether to concatenate the raw input with the reservoir trace before the readout.

TYPE: bool DEFAULT: True

readout

A built-in name ("ridge", "cholesky", "cg", "svd", "pinv", "incremental", "rls", "fista", "lsmr") or a resdag.layers.readouts.ReadoutLayer subclass. Additional solver options go in readout_kwargs.

TYPE: str or type[ReadoutLayer] DEFAULT: "ridge"

readout_alpha

Ridge regularization for the readout.

TYPE: float DEFAULT: 1e-6

readout_bias

Whether to use a bias in the readout.

TYPE: bool DEFAULT: True

readout_name

Name for the readout layer (the target key in training).

TYPE: str DEFAULT: "output"

readout_kwargs

Extra readout options, such as trainable=True, solver, state_noise or gram_dtype. Architecture dimensions are fixed.

TYPE: dict DEFAULT: None

**reservoir_kwargs

Additional keyword arguments forwarded to resdag.layers.reservoirs.lif.LIFReservoirLayer (e.g. bias_scaling, seed, input_initializer).

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION
`resdag.core.ESNModel`

Configured LSM model ready for driven training and inference.

RAISES DESCRIPTION
ValueError

If output_size is not a positive integer, or readout is an unknown string key.

TypeError

If readout is neither a known string key nor a resdag.layers.readouts.ReadoutLayer subclass.

Examples:

>>> from resdag.models import lsm
>>> model = lsm(reservoir_size=300, feedback_size=1, output_size=1, seed=0)
See Also

resdag.models.classic_esn : Traditional leaky ESN with the same wiring. resdag.models.eusn : Euler State Network (another input-driven reservoir). resdag.layers.reservoirs.lif.LIFReservoirLayer : The spiking reservoir layer.

Source code in src/resdag/models/lsm.py
 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
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
def lsm(
    reservoir_size: int,
    feedback_size: int,
    output_size: int,
    input_size: int | None = None,
    input_initializer: InitializerSpec | None = None,
    # Reservoir (LIF) params
    tau_mem: float = 20.0,
    tau_syn: float = 10.0,
    dt: float = 1.0,
    synaptic_current: bool = False,
    v_threshold: float = 1.0,
    reset: str = "subtract",
    surrogate_beta: float = 10.0,
    trace_decay: float = 0.9,
    topology: TopologySpec | None = None,
    spectral_radius: float = 0.9,
    feedback_initializer: InitializerSpec | None = None,
    bias: bool = True,
    trainable: bool = False,
    concat_input: bool = True,
    # Readout params
    readout: ReadoutSpec = "ridge",
    readout_alpha: float = 1e-6,
    readout_bias: bool = True,
    readout_name: str = "output",
    readout_kwargs: dict[str, Any] | None = None,
    # Extra reservoir kwargs
    **reservoir_kwargs: Any,
) -> ESNModel:
    r"""Build a spiking Liquid State Machine (LSM) model.

    The reservoir is a recurrent network of leaky integrate-and-fire neurons
    (`resdag.layers.reservoirs.lif.LIFReservoirLayer`); its real-valued
    synaptic-trace output is concatenated with the raw input and read out by a
    ridge regression, following the classic-ESN wiring:

    ```text
    Input -> LIFReservoirLayer -> Concatenate(Input, trace) -> Readout
    ```

    **Important.**

    This is an **input-driven** reservoir (Maass 2002), *not* a closed-loop
    chaos forecaster — the reservoir output is a filtered spike trace, not the
    feedback variable, so it cannot autoregress on itself. Its use is driven
    regression / classification, where a readout maps the filtered liquid
    state to a target. For autoregressive chaotic forecasting use
    `resdag.models.ott_esn`, `resdag.models.classic_esn`, or
    `resdag.models.es2n`. Continuous inputs enter as injected current.

    Parameters
    ----------
    reservoir_size : int
        Number of spiking units in the liquid.
    feedback_size : int
        Number of input features driving the reservoir.
    output_size : int
        Number of output (target) features.
    input_size : int or None, optional
        Dimension of an optional second driving input.  When given, the model
        takes two inputs `(feedback, driver)`; the driver feeds the reservoir
        but is kept out of the input concatenation, so the readout
        `in_features` stays `feedback_size + reservoir_size`.
    input_initializer : InitializerSpec, optional
        Initializer for the driving-input weights.  Only used when `input_size`
        is given.
    tau_mem : float, default=20.0
        Membrane time constant $\tau_\text{mem}$ (in units of `dt`).
        Sets the membrane decay $\beta = e^{-\Delta t/\tau_\text{mem}}$ —
        longer values give longer fading memory.
    tau_syn : float, default=10.0
        Synaptic time constant $\tau_\text{syn}$.  Only used when
        `synaptic_current=True` (CuBa-LIF).
    dt : float, default=1.0
        Integration timestep $\Delta t$.
    synaptic_current : bool, default=False
        If `True`, use the second-order current-based LIF (CuBa-LIF), which
        adds an explicit synaptic-current state and smoother temporal filtering.
    v_threshold : float, default=1.0
        Firing threshold.
    reset : {'subtract', 'zero'}, default='subtract'
        Membrane reset on a spike (soft subtract vs hard zero).
    surrogate_beta : float, default=10.0
        Fast-sigmoid surrogate slope for the straight-through spike gradient
        (only matters when `trainable=True`).
    trace_decay : float, default=0.9
        Decay $\kappa$ of the low-pass readout trace
        $r_t = \kappa r_{t-1} + s_t$ — the real-valued signal the readout
        regresses on.
    topology : TopologySpec, optional
        Topology for the recurrent spike-coupling weight `W_rec`.  Accepts a
        registry name, a `(name, params)` tuple, a callable, or a configured
        `resdag.init.topology.TopologyInitializer`.
    spectral_radius : float, default=0.9
        Target spectral radius for `W_rec` (recurrent spike-coupling strength).
    feedback_initializer : InitializerSpec, optional
        Initializer for the feedback weights.
    bias : bool, default=True
        Whether to use a bias current in the reservoir.
    trainable : bool, default=False
        Whether the reservoir weights are trainable (via the surrogate spike
        gradient).  A frozen liquid + fitted readout is the classic LSM; set
        `True` to fine-tune the liquid with SGD.
    concat_input : bool, default=True
        Whether to concatenate the raw input with the reservoir trace before the
        readout.
    readout : str or type[ReadoutLayer], default="ridge"
        A built-in name (`"ridge"`, `"cholesky"`, `"cg"`, `"svd"`,
        `"pinv"`, `"incremental"`, `"rls"`, `"fista"`, `"lsmr"`) or a
        `resdag.layers.readouts.ReadoutLayer` subclass. Additional
        solver options go in `readout_kwargs`.
    readout_alpha : float, default=1e-6
        Ridge regularization for the readout.
    readout_bias : bool, default=True
        Whether to use a bias in the readout.
    readout_name : str, default="output"
        Name for the readout layer (the target key in training).
    readout_kwargs : dict, optional
        Extra readout options, such as `trainable=True`, `solver`,
        `state_noise` or `gram_dtype`. Architecture dimensions are fixed.
    **reservoir_kwargs : Any
        Additional keyword arguments forwarded to
        `resdag.layers.reservoirs.lif.LIFReservoirLayer` (e.g. `bias_scaling`,
        `seed`, `input_initializer`).

    Returns
    -------
    `resdag.core.ESNModel`
        Configured LSM model ready for driven training and inference.

    Raises
    ------
    ValueError
        If `output_size` is not a positive integer, or `readout` is an
        unknown string key.
    TypeError
        If `readout` is neither a known string key nor a
        `resdag.layers.readouts.ReadoutLayer` subclass.

    Examples
    --------
    >>> from resdag.models import lsm
    >>> model = lsm(reservoir_size=300, feedback_size=1, output_size=1, seed=0)

    See Also
    --------
    resdag.models.classic_esn : Traditional leaky ESN with the same wiring.
    resdag.models.eusn : Euler State Network (another input-driven reservoir).
    resdag.layers.reservoirs.lif.LIFReservoirLayer : The spiking reservoir layer.
    """
    if output_size <= 0:
        raise ValueError(f"output_size must be a positive integer, got {output_size!r}")

    # Resolve the readout up front so an invalid spec fails before construction.

    inp = reservoir_input(
        feedback_size, dtype=reservoir_kwargs.get("dtype"), device=reservoir_kwargs.get("device")
    )
    driver = (
        reservoir_input(
            input_size, dtype=reservoir_kwargs.get("dtype"), device=reservoir_kwargs.get("device")
        )
        if input_size
        else None
    )

    reservoir = LIFReservoirLayer(
        reservoir_size=reservoir_size,
        feedback_size=feedback_size,
        input_size=input_size,
        tau_mem=tau_mem,
        tau_syn=tau_syn,
        dt=dt,
        synaptic_current=synaptic_current,
        v_threshold=v_threshold,
        reset=reset,
        surrogate_beta=surrogate_beta,
        trace_decay=trace_decay,
        spectral_radius=spectral_radius,
        topology=topology,
        feedback_initializer=feedback_initializer,
        input_initializer=input_initializer,
        bias=bias,
        trainable=trainable,
        **reservoir_kwargs,
    )

    output: SymbolicTensor = reservoir(inp) if driver is None else reservoir(inp, driver)
    model_inputs = inp if driver is None else [inp, driver]

    if concat_input:
        output = Concatenate()(inp, output)
        readout_in_features = feedback_size + reservoir_size
    else:
        readout_in_features = reservoir_size

    readout_layer = _make_readout(
        readout,
        in_features=readout_in_features,
        out_features=output_size,
        bias=readout_bias,
        alpha=readout_alpha,
        name=readout_name,
        readout_kwargs=readout_kwargs,
    ).to(device=reservoir.weight_feedback.device, dtype=reservoir.weight_feedback.dtype)(output)

    return ESNModel(model_inputs, readout_layer)

ott_esn

ott_esn(
    reservoir_size: int,
    feedback_size: int,
    output_size: int,
    input_size: int | None = None,
    input_initializer: InitializerSpec | None = None,
    topology: TopologySpec | None = None,
    spectral_radius: float = 0.9,
    leak_rate: float = 1.0,
    feedback_initializer: InitializerSpec | None = None,
    activation: str = "tanh",
    bias: bool = True,
    trainable: bool = False,
    readout: ReadoutSpec = "ridge",
    readout_alpha: float = 1e-06,
    readout_bias: bool = True,
    readout_name: str = "output",
    readout_kwargs: dict[str, Any] | None = None,
    **reservoir_kwargs: Any
) -> ESNModel

Build Ott's ESN model with state augmentation.

This model follows the architecture proposed by Edward Ott, which augments reservoir states by squaring even-indexed units and concatenating with input. This augmentation helps capture higher-order dynamics in chaotic systems.

Architecture:

Input -> Reservoir -> SelectiveExponentiation -> Concatenate(Input, Augmented) -> Readout
PARAMETER DESCRIPTION
reservoir_size

Number of units in the reservoir.

TYPE: int

feedback_size

Dimension of feedback signal (input features).

TYPE: int

output_size

Dimension of output signal.

TYPE: int

input_size

Dimension of an optional driving (exogenous) input. When given, the model takes two inputs (feedback, driver) and the driver feeds the reservoir alongside the autoregressive feedback. The driver is kept out of the input concatenation, so the readout in_features stays feedback_size + reservoir_size. None (default) builds a feedback-only model, unchanged from previous behavior.

TYPE: int or None DEFAULT: None

input_initializer

Initializer for the driving-input weights. Same format as feedback_initializer. Only used when input_size is given.

TYPE: str, tuple, or InputFeedbackInitializer DEFAULT: None

topology

Topology for recurrent weights. Accepts:

  • str: Registry name (e.g., "erdos_renyi")
  • tuple: (name, params) like ("watts_strogatz", {"k": 6, "p": 0.1})
  • TopologyInitializer: Pre-configured object

TYPE: str, tuple, or TopologyInitializer DEFAULT: None

spectral_radius

Target spectral radius for recurrent weights.

TYPE: float DEFAULT: 0.9

leak_rate

Leaky integration rate. 1.0 = no leaking (standard ESN).

TYPE: float DEFAULT: 1.0

feedback_initializer

Initializer for feedback weights. Same format as topology.

TYPE: str, tuple, or InputFeedbackInitializer DEFAULT: None

activation

Activation function for reservoir neurons.

TYPE: (tanh, relu, sigmoid, identity) DEFAULT: 'tanh'

bias

Whether to include bias in reservoir.

TYPE: bool DEFAULT: True

trainable

If True, reservoir weights are trainable via backpropagation.

TYPE: bool DEFAULT: False

readout

A built-in name ("ridge", "cholesky", "cg", "svd", "pinv", "incremental", "rls", "fista", "lsmr") or a resdag.layers.readouts.ReadoutLayer subclass. Additional solver options go in readout_kwargs.

TYPE: str or type[ReadoutLayer] DEFAULT: "ridge"

readout_alpha

L2 regularization strength for ridge regression in readout.

TYPE: float DEFAULT: 1e-6

readout_bias

Whether to include bias in readout layer.

TYPE: bool DEFAULT: True

readout_name

Name for the readout layer. Used as target key in training.

TYPE: str DEFAULT: 'output'

readout_kwargs

Extra readout constructor options, including trainable, rcond, state_noise or gram_dtype. Architecture widths are fixed.

TYPE: dict DEFAULT: None

**reservoir_kwargs

Additional keyword arguments passed to ESNLayer.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION
ESNModel

Configured Ott ESN model ready for training and inference.

Examples:

Basic usage:

>>> from resdag.models import ott_esn
>>> model = ott_esn(
...     reservoir_size=500,
...     feedback_size=3,
...     output_size=3,
... )
>>> model.summary()

With custom topology:

>>> from resdag.init.topology import get_topology
>>> model = ott_esn(
...     reservoir_size=500,
...     feedback_size=3,
...     output_size=3,
...     topology=get_topology("watts_strogatz", k=4, p=0.3),
...     spectral_radius=0.95,
... )

Training and forecasting:

>>> from resdag.training import ESNTrainer
>>> trainer = ESNTrainer(model)
>>> trainer.fit(
...     warmup_inputs=(warmup,),
...     train_inputs=(train,),
...     targets={"output": target},
... )
>>> predictions = model.forecast(forecast_warmup, horizon=100)
See Also

classic_esn : Traditional ESN without state augmentation. resdag.training.ESNTrainer : Trainer for fitting readout. resdag.init.topology.get_topology : Get topology by name.

Source code in src/resdag/models/ott_esn.py
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 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
 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
@record_recipe("ott")
def ott_esn(
    reservoir_size: int,
    feedback_size: int,
    output_size: int,
    input_size: int | None = None,
    input_initializer: InitializerSpec | None = None,
    # Reservoir params
    topology: TopologySpec | None = None,
    spectral_radius: float = 0.9,
    leak_rate: float = 1.0,
    feedback_initializer: InitializerSpec | None = None,
    activation: str = "tanh",
    bias: bool = True,
    trainable: bool = False,
    # Readout params
    readout: ReadoutSpec = "ridge",
    readout_alpha: float = 1e-6,
    readout_bias: bool = True,
    readout_name: str = "output",
    readout_kwargs: dict[str, Any] | None = None,
    # Extra reservoir kwargs
    **reservoir_kwargs: Any,
) -> ESNModel:
    """
    Build Ott's ESN model with state augmentation.

    This model follows the architecture proposed by Edward Ott, which augments
    reservoir states by squaring even-indexed units and concatenating with input.
    This augmentation helps capture higher-order dynamics in chaotic systems.

    Architecture:

    ```text
    Input -> Reservoir -> SelectiveExponentiation -> Concatenate(Input, Augmented) -> Readout
    ```

    Parameters
    ----------
    reservoir_size : int
        Number of units in the reservoir.
    feedback_size : int
        Dimension of feedback signal (input features).
    output_size : int
        Dimension of output signal.
    input_size : int or None, optional
        Dimension of an optional driving (exogenous) input.  When given, the
        model takes two inputs `(feedback, driver)` and the driver feeds the
        reservoir alongside the autoregressive feedback.  The driver is kept out
        of the input concatenation, so the readout `in_features` stays
        `feedback_size + reservoir_size`.  `None` (default) builds a
        feedback-only model, unchanged from previous behavior.
    input_initializer : str, tuple, or InputFeedbackInitializer, optional
        Initializer for the driving-input weights.  Same format as
        `feedback_initializer`.  Only used when `input_size` is given.
    topology : str, tuple, or TopologyInitializer, optional
        Topology for recurrent weights. Accepts:

        - str: Registry name (e.g., `"erdos_renyi"`)
        - tuple: `(name, params)` like `("watts_strogatz", {"k": 6, "p": 0.1})`
        - TopologyInitializer: Pre-configured object

    spectral_radius : float, default=0.9
        Target spectral radius for recurrent weights.
    leak_rate : float, default=1.0
        Leaky integration rate. 1.0 = no leaking (standard ESN).
    feedback_initializer : str, tuple, or InputFeedbackInitializer, optional
        Initializer for feedback weights. Same format as `topology`.
    activation : {'tanh', 'relu', 'sigmoid', 'identity'}, default='tanh'
        Activation function for reservoir neurons.
    bias : bool, default=True
        Whether to include bias in reservoir.
    trainable : bool, default=False
        If True, reservoir weights are trainable via backpropagation.
    readout : str or type[ReadoutLayer], default="ridge"
        A built-in name (`"ridge"`, `"cholesky"`, `"cg"`, `"svd"`,
        `"pinv"`, `"incremental"`, `"rls"`, `"fista"`, `"lsmr"`) or a
        `resdag.layers.readouts.ReadoutLayer` subclass. Additional
        solver options go in `readout_kwargs`.
    readout_alpha : float, default=1e-6
        L2 regularization strength for ridge regression in readout.
    readout_bias : bool, default=True
        Whether to include bias in readout layer.
    readout_name : str, default='output'
        Name for the readout layer. Used as target key in training.
    readout_kwargs : dict, optional
        Extra readout constructor options, including `trainable`, `rcond`,
        `state_noise` or `gram_dtype`. Architecture widths are fixed.
    **reservoir_kwargs
        Additional keyword arguments passed to `ESNLayer`.

    Returns
    -------
    ESNModel
        Configured Ott ESN model ready for training and inference.

    Examples
    --------
    Basic usage:

    >>> from resdag.models import ott_esn
    >>> model = ott_esn(
    ...     reservoir_size=500,
    ...     feedback_size=3,
    ...     output_size=3,
    ... )
    >>> model.summary()

    With custom topology:

    >>> from resdag.init.topology import get_topology
    >>> model = ott_esn(
    ...     reservoir_size=500,
    ...     feedback_size=3,
    ...     output_size=3,
    ...     topology=get_topology("watts_strogatz", k=4, p=0.3),
    ...     spectral_radius=0.95,
    ... )

    Training and forecasting:

    >>> from resdag.training import ESNTrainer
    >>> trainer = ESNTrainer(model)
    >>> trainer.fit(
    ...     warmup_inputs=(warmup,),
    ...     train_inputs=(train,),
    ...     targets={"output": target},
    ... )
    >>> predictions = model.forecast(forecast_warmup, horizon=100)

    See Also
    --------
    classic_esn : Traditional ESN without state augmentation.
    resdag.training.ESNTrainer : Trainer for fitting readout.
    resdag.init.topology.get_topology : Get topology by name.
    """
    # Ott augmentation: square even-indexed reservoir units, concatenate input.
    return _esn_builder(
        reservoir_size=reservoir_size,
        feedback_size=feedback_size,
        output_size=output_size,
        augment=lambda: SelectiveExponentiation(index=0, exponent=2.0),
        concat_input=True,
        input_size=input_size,
        input_initializer=input_initializer,
        topology=topology,
        spectral_radius=spectral_radius,
        leak_rate=leak_rate,
        feedback_initializer=feedback_initializer,
        activation=activation,
        bias=bias,
        trainable=trainable,
        readout=readout,
        readout_alpha=readout_alpha,
        readout_bias=readout_bias,
        readout_name=readout_name,
        readout_kwargs=readout_kwargs,
        **reservoir_kwargs,
    )

ParallelESNModel

ParallelESNModel(
    reservoir: ESNLayer,
    readout: ReadoutLayer,
    input_dim: int,
    core_width: int,
    halo: int,
)

Bases: Module

Parallel local-state reservoir for spatiotemporal forecasting.

Holds one shared-weight resdag.layers.ESNLayer (advanced batched over patches) and one weight-tied resdag.layers.readouts.ReadoutLayer (fitted once over the pooled per-patch data), plus the patch geometry (input_dim, core_width, halo). Build it with parallel_esn rather than directly.

The public workflow mirrors the rest of the library — fit then forecast — but the forecasting is spatial-autoregressive: it stitches per-patch core predictions into the full field and re-windows every step, rather than feeding a single output straight back.

PARAMETER DESCRIPTION
reservoir

The shared reservoir. Its feedback_size must equal core_width + 2 * halo (the per-patch input width).

TYPE: ESNLayer

readout

The weight-tied readout. Its in_features must equal the reservoir size and its out_features must equal core_width.

TYPE: ReadoutLayer

input_dim

Full spatial dimension D of the modelled field.

TYPE: int

core_width

Core width w each patch predicts (P = input_dim // core_width).

TYPE: int

halo

Halo width g (neighbouring cells read on each side of the core).

TYPE: int

ATTRIBUTE DESCRIPTION
reservoir

The shared reservoir layer.

TYPE: ESNLayer

readout

The weight-tied readout layer.

TYPE: ReadoutLayer

n_patches

Number of patches P = input_dim // core_width.

TYPE: int

See Also

parallel_esn : Factory that builds and wires this class.

Source code in src/resdag/models/parallel_esn.py
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
def __init__(
    self,
    reservoir: ESNLayer,
    readout: ReadoutLayer,
    input_dim: int,
    core_width: int,
    halo: int,
) -> None:
    super().__init__()
    patch_index = _patch_gather_index(input_dim, core_width, halo).to(
        device=reservoir.reference_device_dtype()[0]
    )
    patch_width = core_width + 2 * halo
    if reservoir.feedback_size != patch_width:
        raise ValueError(
            f"reservoir.feedback_size ({reservoir.feedback_size}) must equal the "
            f"per-patch input width core_width + 2*halo = {patch_width}."
        )
    if readout.out_features != core_width:
        raise ValueError(
            f"readout.out_features ({readout.out_features}) must equal core_width "
            f"({core_width}) — each patch predicts only its core region."
        )
    if readout.in_features != reservoir.reservoir_size:
        raise ValueError(
            f"readout.in_features ({readout.in_features}) must equal the reservoir "
            f"size ({reservoir.reservoir_size})."
        )

    self.reservoir = reservoir
    self.readout = readout
    self.input_dim = input_dim
    self.core_width = core_width
    self.halo = halo
    self.n_patches = input_dim // core_width
    # Non-persistent: rebuilt cheaply from geometry, moves with ``.to()``.
    self.register_buffer(
        "patch_index",
        patch_index,
        persistent=False,
    )

forward

forward(series: Tensor, *, reset: bool = False) -> Tensor

Predict each timestep, preserving gradients through the model.

Accepts (batch, time, input_dim) and returns that shape. Reservoir state carries across calls; use reset=True for independent batches. This teacher-forced path composes with ordinary PyTorch modules and optimizers. Use forecast for an autonomous rollout.

Source code in src/resdag/models/parallel_esn.py
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
def forward(self, series: torch.Tensor, *, reset: bool = False) -> torch.Tensor:
    """Predict each timestep, preserving gradients through the model.

    Accepts `(batch, time, input_dim)` and returns that shape. Reservoir
    state carries across calls; use `reset=True` for independent batches.
    This teacher-forced path composes with ordinary PyTorch modules and
    optimizers. Use `forecast` for an autonomous rollout.
    """
    validate_sequence_inputs(
        (series,), feature_sizes=(self.input_dim,), reference=module_reference(self)
    )
    if reset:
        self.reset_reservoirs()
    states = self.reservoir(self.window(series))
    batch, timesteps = series.shape[:2]
    cores = cast(torch.Tensor, self.readout(states))
    return (
        cores.reshape(batch, self.n_patches, timesteps, self.core_width)
        .permute(0, 2, 1, 3)
        .reshape(batch, timesteps, self.input_dim)
    )

forward_stateless

forward_stateless(
    *inputs: Tensor, states: Mapping[str, Tensor] | None = None, compile: bool = False
) -> tuple[Tensor, ReservoirStates]

Predict independently or continue explicit per-patch recurrent states.

Pass one (batch, time, input_dim) field. The returned reservoir state folds the patches into its batch axis, with shape (batch * n_patches, reservoir_size). State tensors retain gradients; this method leaves the model's stored streaming states untouched.

Source code in src/resdag/models/parallel_esn.py
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
def forward_stateless(
    self,
    *inputs: torch.Tensor,
    states: Mapping[str, torch.Tensor] | None = None,
    compile: bool = False,
) -> tuple[torch.Tensor, ReservoirStates]:
    """Predict independently or continue explicit per-patch recurrent states.

    Pass one `(batch, time, input_dim)` field. The returned `reservoir`
    state folds the patches into its batch axis, with shape
    `(batch * n_patches, reservoir_size)`. State tensors retain gradients;
    this method leaves the model's stored streaming states untouched.
    """
    validate_sequence_inputs(
        inputs, feature_sizes=(self.input_dim,), reference=module_reference(self)
    )
    from resdag.core._hooks import call_with_states, has_execution_hooks

    if has_execution_hooks(self):
        return cast(
            tuple[torch.Tensor, ReservoirStates],
            call_with_states(self, inputs, states, {"reservoir": "reservoir"}, compile=compile),
        )
    series = inputs[0]
    patches = self.window(series)
    if states is None:
        state = self.reservoir.cell.init_state(patches.shape[0], patches.device, patches.dtype)
    else:
        if set(states) != {"reservoir"}:
            raise ValueError("Reservoir state keys must be exactly ['reservoir']")
        state = states["reservoir"]
        if not isinstance(state, torch.Tensor):
            raise TypeError("State for 'reservoir' must be a torch.Tensor")
        self.reservoir.cell.validate_state(state)
        if state.shape[0] != patches.shape[0]:
            raise ValueError("State batch size must equal batch * n_patches")
        if state.device != patches.device or state.dtype != patches.dtype:
            raise ValueError("State must match the input device and dtype")
    features, final = self.reservoir.forward_stateless([patches], state, compile=compile)
    batch, timesteps = series.shape[:2]
    cores = cast(torch.Tensor, self.readout(features))
    output = (
        cores.reshape(batch, self.n_patches, timesteps, self.core_width)
        .permute(0, 2, 1, 3)
        .reshape(batch, timesteps, self.input_dim)
    )
    return output, {"reservoir": final}

as_module

as_module(*, stateful: bool = False) -> ReservoirModelModule

Share this complete trained model with a larger PyTorch pipeline.

Source code in src/resdag/models/parallel_esn.py
306
307
308
def as_module(self, *, stateful: bool = False) -> ReservoirModelModule:
    """Share this complete trained model with a larger PyTorch pipeline."""
    return ReservoirModelModule(self, stateful=stateful)

window

window(series: Tensor) -> Tensor

Window a full (batch, T, D) field into per-patch inputs.

Gathers, for every patch, its core_width + 2 * halo periodic cells in one indexing op, then folds the patch axis into the batch axis so the result drops straight into the shared reservoir as a batched sequence.

PARAMETER DESCRIPTION
series

Full field of shape (batch, T, input_dim).

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Windowed input of shape (batch * P, T, core_width + 2 * halo) — the patch axis is folded into the leading (reservoir-batch) axis.

Source code in src/resdag/models/parallel_esn.py
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
def window(self, series: torch.Tensor) -> torch.Tensor:
    """Window a full `(batch, T, D)` field into per-patch inputs.

    Gathers, for every patch, its `core_width + 2 * halo` periodic cells in
    one indexing op, then folds the patch axis into the batch axis so the
    result drops straight into the shared reservoir as a batched sequence.

    Parameters
    ----------
    series : torch.Tensor
        Full field of shape `(batch, T, input_dim)`.

    Returns
    -------
    torch.Tensor
        Windowed input of shape `(batch * P, T, core_width + 2 * halo)` —
        the patch axis is folded into the leading (reservoir-batch) axis.
    """
    if series.dim() != 3 or series.shape[-1] != self.input_dim:
        raise ValueError(
            f"series must be 3-D (batch, T, input_dim={self.input_dim}); "
            f"got shape {tuple(series.shape)}."
        )
    # series: (B, T, D) -> gather patch cells -> (B, T, P, w+2g).
    windowed = series[..., self.patch_index]
    b, t, n_patches, patch_width = windowed.shape
    # Move patches next to the batch axis and fold them in: (B*P, T, w+2g).
    windowed = windowed.permute(0, 2, 1, 3).reshape(b * n_patches, t, patch_width)
    return windowed

stitch

stitch(patch_cores: Tensor) -> Tensor

Assemble per-patch core predictions into the full field.

Inverse of window for the core regions: patch p owns cores [p*w : (p+1)*w] of the full field, so concatenating the patches' core predictions along the spatial axis reconstructs the whole D-wide state. With non-overlapping cores this is a contiguous reshape (no averaging needed).

PARAMETER DESCRIPTION
patch_cores

Per-patch core predictions of shape (batch, P, core_width).

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Full field of shape (batch, input_dim).

Source code in src/resdag/models/parallel_esn.py
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
def stitch(self, patch_cores: torch.Tensor) -> torch.Tensor:
    """Assemble per-patch core predictions into the full field.

    Inverse of `window` for the core regions: patch `p` owns cores
    `[p*w : (p+1)*w]` of the full field, so concatenating the patches' core
    predictions along the spatial axis reconstructs the whole `D`-wide
    state.  With non-overlapping cores this is a contiguous reshape (no
    averaging needed).

    Parameters
    ----------
    patch_cores : torch.Tensor
        Per-patch core predictions of shape `(batch, P, core_width)`.

    Returns
    -------
    torch.Tensor
        Full field of shape `(batch, input_dim)`.
    """
    b = patch_cores.shape[0]
    return patch_cores.reshape(b, self.input_dim)

reset_reservoirs

reset_reservoirs() -> None

Reset the shared reservoir's per-patch states (lazy re-init).

Source code in src/resdag/models/parallel_esn.py
370
371
372
def reset_reservoirs(self) -> None:
    """Reset the shared reservoir's per-patch states (lazy re-init)."""
    self.reservoir.reset_state()

get_state

get_state() -> ReservoirStates

Return a copy of the initialized, patch-batched streaming state.

Source code in src/resdag/models/parallel_esn.py
374
375
376
377
def get_state(self) -> ReservoirStates:
    """Return a copy of the initialized, patch-batched streaming state."""
    state = self.reservoir.get_state()
    return {} if state is None else {"reservoir": state}

set_state

set_state(states: Mapping[str, Tensor], strict: bool = True) -> None

Restore the named recurrent state on the model's device and dtype.

Source code in src/resdag/models/parallel_esn.py
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
def set_state(self, states: Mapping[str, torch.Tensor], strict: bool = True) -> None:
    """Restore the named recurrent state on the model's device and dtype."""
    if strict and set(states) != {"reservoir"}:
        raise KeyError("Reservoir state keys must be exactly ['reservoir']")
    if "reservoir" in states:
        import warnings

        device, dtype = self.reservoir.reference_device_dtype()
        state = states["reservoir"]
        if state.device != device or state.dtype != dtype:
            warnings.warn(
                f"State for 'reservoir' moved/cast to device={device}, dtype={dtype}",
                UserWarning,
                stacklevel=2,
            )
        self.reservoir.set_state(state.to(device=device, dtype=dtype))

get_reservoir_states

get_reservoir_states() -> ReservoirStates

Return the named recurrent state; alias of get_state.

Source code in src/resdag/models/parallel_esn.py
396
397
398
def get_reservoir_states(self) -> ReservoirStates:
    """Return the named recurrent state; alias of `get_state`."""
    return self.get_state()

set_reservoir_states

set_reservoir_states(states: Mapping[str, Tensor], strict: bool = True) -> None

Restore named recurrent state; alias of set_state.

Source code in src/resdag/models/parallel_esn.py
400
401
402
def set_reservoir_states(self, states: Mapping[str, torch.Tensor], strict: bool = True) -> None:
    """Restore named recurrent state; alias of `set_state`."""
    self.set_state(states, strict=strict)

fit

fit(warmup: Tensor, train: Tensor, targets: Tensor, *, reset: bool = True) -> None

Fit the weight-tied readout over all patches in one pooled solve.

Windows warmup / train into per-patch inputs, runs them through the shared reservoir (batched over batch * P), and fits the single readout on the pooled (reservoir_state -> core_target) pairs from every patch and timestep — the weight-tied readout of Pathak et al.

PARAMETER DESCRIPTION
warmup

Teacher-forced warmup field of shape (batch, warmup_steps, D) used only to synchronise the reservoir states.

TYPE: Tensor

train

Training field of shape (batch, train_steps, D) whose reservoir states are regressed onto targets.

TYPE: Tensor

targets

Next-step field of shape (batch, train_steps, D) — typically train shifted one step ahead. Each patch is supervised on its own core slice of this field.

TYPE: Tensor

reset

If True, reset the reservoir states before warmup.

TYPE: bool DEFAULT: True

RAISES DESCRIPTION
ValueError

If any input is not 3-D, if their feature dimension is not input_dim, or if train and targets disagree on batch/length.

Source code in src/resdag/models/parallel_esn.py
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
479
480
481
482
483
484
485
486
def fit(
    self,
    warmup: torch.Tensor,
    train: torch.Tensor,
    targets: torch.Tensor,
    *,
    reset: bool = True,
) -> None:
    """Fit the weight-tied readout over all patches in one pooled solve.

    Windows `warmup` / `train` into per-patch inputs, runs them through
    the shared reservoir (batched over `batch * P`), and fits the single
    readout on the pooled `(reservoir_state -> core_target)` pairs from
    every patch and timestep — the weight-tied readout of Pathak et al.

    Parameters
    ----------
    warmup : torch.Tensor
        Teacher-forced warmup field of shape `(batch, warmup_steps, D)`
        used only to synchronise the reservoir states.
    train : torch.Tensor
        Training field of shape `(batch, train_steps, D)` whose reservoir
        states are regressed onto `targets`.
    targets : torch.Tensor
        Next-step field of shape `(batch, train_steps, D)` — typically
        `train` shifted one step ahead.  Each patch is supervised on its
        own core slice of this field.
    reset : bool, default=True
        If `True`, reset the reservoir states before warmup.

    Raises
    ------
    ValueError
        If any input is not 3-D, if their feature dimension is not
        `input_dim`, or if `train` and `targets` disagree on
        batch/length.
    """
    for name, arr in (("warmup", warmup), ("train", train), ("targets", targets)):
        if arr.dim() != 3:
            raise ValueError(f"{name} must be 3-D (batch, T, D); got shape {tuple(arr.shape)}.")
        if arr.shape[-1] != self.input_dim:
            raise ValueError(
                f"{name} has feature dim {arr.shape[-1]}, expected input_dim={self.input_dim}."
            )
    if train.shape[:2] != targets.shape[:2]:
        raise ValueError(
            f"train and targets must share (batch, T); got {tuple(train.shape[:2])} "
            f"vs {tuple(targets.shape[:2])}."
        )
    reference = module_reference(self)
    for label, tensor in (("warmup", warmup), ("train", train), ("targets", targets)):
        validate_sequence_inputs(
            (tensor,),
            feature_sizes=(self.input_dim,),
            reference=reference,
            label=label,
            allow_empty=label == "warmup",
        )
    if warmup.shape[0] != train.shape[0]:
        raise ValueError("warmup and train must have the same batch size")

    if reset:
        self.reset_reservoirs()

    with torch.no_grad():
        # Warmup: synchronise the per-patch reservoir states.
        self.reservoir(self.window(warmup))
        # Train pass: collect reservoir states for every patch and step.
        states = self.reservoir(self.window(train))  # (B*P, train_steps, N)

    # Per-patch core targets: window the target field and keep only the core
    # columns (offsets [halo, halo + core_width)).  Same (B*P, T) folding as
    # the states, so state[i] and target[i] are the same patch/step pair.
    windowed_targets = self.window(targets)  # (B*P, T, w+2g)
    core_targets = windowed_targets[..., self._cores_from_index()]  # (B*P, T, w)

    # One pooled ridge solve over all patches (weight-tied readout).  fit()
    # flattens (B*P, T, .) -> (B*P*T, .) internally.
    self.readout.fit(states, core_targets)

forecast

forecast(
    warmup: Tensor,
    *,
    horizon: int,
    initial_feedback: Tensor | None = None,
    reset: bool = True,
    return_warmup: bool = False,
    alignment: ForecastAlignment = "next"
) -> Tensor

Predict the next full fields after the observed warmup.

Inputs have shape (batch, time, input_dim) and results have shape (batch, horizon, input_dim). Slot zero is the final warmup prediction, estimating the immediate unseen field. Each later step feeds the previous prediction through the batched patches. horizon is a positive integer.

initial_feedback is a distinct extra field consumed after all warmup fields, shaped (batch, 1, input_dim). It also permits empty history; use reset=False to continue states with the previous final prediction as this seed. The final returned prediction has not yet been consumed.

return_warmup=True prepends historical predictions, giving length warmup_steps - 1 + horizon. Explicit seeds give warmup_steps + horizon. alignment="legacy" uses the old low-level ESN convention: omit the final warmup prediction, then generate horizon steps, giving a warmup_steps + horizon result when historical predictions are included. The default future timing already matches earlier ParallelESN releases; their return_warmup prefix contained raw observations instead.

Source code in src/resdag/models/parallel_esn.py
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
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
def forecast(
    self,
    warmup: torch.Tensor,
    *,
    horizon: int,
    initial_feedback: torch.Tensor | None = None,
    reset: bool = True,
    return_warmup: bool = False,
    alignment: ForecastAlignment = "next",
) -> torch.Tensor:
    """Predict the next full fields after the observed `warmup`.

    Inputs have shape `(batch, time, input_dim)` and results have shape
    `(batch, horizon, input_dim)`. Slot zero is the final warmup prediction,
    estimating the immediate unseen field. Each later step feeds the previous
    prediction through the batched patches. `horizon` is a positive integer.

    `initial_feedback` is a distinct extra field consumed after all warmup
    fields, shaped `(batch, 1, input_dim)`. It also permits empty history;
    use `reset=False` to continue states with the previous final prediction
    as this seed. The final returned prediction has not yet been consumed.

    `return_warmup=True` prepends historical *predictions*, giving length
    `warmup_steps - 1 + horizon`. Explicit seeds give `warmup_steps + horizon`.
    `alignment="legacy"` uses the old low-level ESN convention: omit the
    final warmup prediction, then generate `horizon` steps, giving a
    `warmup_steps + horizon` result when historical predictions are included.
    The default future timing already matches earlier ParallelESN releases;
    their `return_warmup` prefix contained raw observations instead.
    """
    inputs, _, horizon, boundary = prepare_forecast_inputs(
        warmup,
        None,
        num_inputs=1,
        horizon=horizon,
        initial_feedback=initial_feedback,
        alignment=alignment,
    )
    warmup = inputs[0]
    if warmup.shape[-1] != self.input_dim:
        raise ValueError(
            f"warmup must have input_dim={self.input_dim} features; got {warmup.shape[-1]}"
        )
    if not self.readout.is_fitted:
        raise ValueError("forecast() requires a fitted readout; call fit() first.")
    from resdag.core._hooks import has_execution_hooks

    hooked = has_execution_hooks(self)
    forward = self if hooked else self.forward
    advance = (
        self._forecast_single_frame
        if not hooked and self._can_forecast_single_frame()
        else forward
    )
    with torch.no_grad():
        warmup_outputs = forward(warmup, reset=reset)
        current = (
            initial_feedback if initial_feedback is not None else warmup_outputs[:, -1:, :]
        )
        outputs = torch.empty(
            warmup.shape[0],
            horizon,
            self.input_dim,
            dtype=warmup_outputs.dtype,
            device=warmup_outputs.device,
        )
        if boundary:
            outputs[:, :1, :] = current
        for t in range(int(boundary), horizon):
            current = advance(current)
            outputs[:, t : t + 1, :] = current
        if return_warmup:
            prefix = warmup_outputs[:, :-1, :] if boundary else warmup_outputs
            return torch.cat((prefix, outputs), dim=1)
        return outputs

save

save(path: str | Path, include_states: bool = False, **metadata: Any) -> None

Save weights and optional recurrent state; recreate the architecture to load.

Source code in src/resdag/models/parallel_esn.py
624
625
626
627
628
629
630
631
def save(
    self,
    path: str | Path,
    include_states: bool = False,
    **metadata: Any,
) -> None:
    """Save weights and optional recurrent state; recreate the architecture to load."""
    save_checkpoint(self, path, include_states, metadata)

load

load(
    path: str | Path,
    strict: bool = True,
    load_states: bool = False,
    map_location: Any = None,
) -> None

Restore a matching model, optionally remapping saved tensor devices.

Source code in src/resdag/models/parallel_esn.py
633
634
635
636
637
638
639
640
641
def load(
    self,
    path: str | Path,
    strict: bool = True,
    load_states: bool = False,
    map_location: Any = None,
) -> None:
    """Restore a matching model, optionally remapping saved tensor devices."""
    load_checkpoint(self, path, strict, load_states, map_location)

load_from_file classmethod

load_from_file(
    path: str | Path,
    model: "ParallelESNModel | None" = None,
    strict: bool = True,
    load_states: bool = False,
    map_location: Any = None,
) -> "ParallelESNModel"

Restore weights into an already constructed matching model.

Source code in src/resdag/models/parallel_esn.py
643
644
645
646
647
648
649
650
651
652
653
654
655
656
@classmethod
def load_from_file(
    cls,
    path: str | Path,
    model: "ParallelESNModel | None" = None,
    strict: bool = True,
    load_states: bool = False,
    map_location: Any = None,
) -> "ParallelESNModel":
    """Restore weights into an already constructed matching model."""
    if model is None:
        raise ValueError("model argument is required")
    model.load(path, strict=strict, load_states=load_states, map_location=map_location)
    return model

save_full

save_full(path: str | Path, **metadata: Any) -> None

Serialize the whole model (architecture + weights + states) to a file.

Mirrors resdag.core.ESNModel.save_full: pickles the entire module so load_full reconstructs it with no pre-built architecture. The file is a torch.save payload loaded back with weights_only=False — only open files you trust.

PARAMETER DESCRIPTION
path

File path to save to. Parent directories are created if needed.

TYPE: str or Path

**metadata

Additional metadata stored alongside the model.

TYPE: Any DEFAULT: {}

Source code in src/resdag/models/parallel_esn.py
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
def save_full(self, path: str | Path, **metadata: Any) -> None:
    """Serialize the whole model (architecture + weights + states) to a file.

    Mirrors `resdag.core.ESNModel.save_full`: pickles the entire module
    so `load_full` reconstructs it with no pre-built architecture.  The
    file is a `torch.save` payload loaded back with `weights_only=False` —
    only open files you trust.

    Parameters
    ----------
    path : str or Path
        File path to save to. Parent directories are created if needed.
    **metadata
        Additional metadata stored alongside the model.
    """
    save_full_model(self, path, metadata)

load_full classmethod

load_full(
    path: str | Path,
    return_metadata: bool = False,
    map_location: Any = None,
    *,
    trusted: bool = False
) -> "ParallelESNModel | tuple[ParallelESNModel, dict[str, Any]]"

Reconstruct a model saved with save_full.

PARAMETER DESCRIPTION
path

File path written by save_full.

TYPE: str or Path

return_metadata

If True, return (model, metadata) instead of just the model.

TYPE: bool DEFAULT: False

map_location

Passed to torch.load to remap storage devices.

TYPE: optional DEFAULT: None

trusted

Explicit opt-in to execute the saved Python. Required for full pickle files; prefer Model.save and resdag.load otherwise.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
ParallelESNModel or tuple of (ParallelESNModel, dict)

The reconstructed model, optionally paired with its metadata.

RAISES DESCRIPTION
ValueError

If the file does not contain a parallel model.

Warnings

Loads with weights_only=False (unpickles arbitrary objects); only call on trusted files.

Source code in src/resdag/models/parallel_esn.py
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
713
714
@classmethod
def load_full(
    cls,
    path: str | Path,
    return_metadata: bool = False,
    map_location: Any = None,
    *,
    trusted: bool = False,
) -> "ParallelESNModel | tuple[ParallelESNModel, dict[str, Any]]":
    """Reconstruct a model saved with `save_full`.

    Parameters
    ----------
    path : str or Path
        File path written by `save_full`.
    return_metadata : bool, default=False
        If `True`, return `(model, metadata)` instead of just the model.
    map_location : optional
        Passed to `torch.load` to remap storage devices.

    trusted : bool, default=False
        Explicit opt-in to execute the saved Python. Required for full
        pickle files; prefer `Model.save` and `resdag.load` otherwise.

    Returns
    -------
    ParallelESNModel or tuple of (ParallelESNModel, dict)
        The reconstructed model, optionally paired with its metadata.

    Raises
    ------
    ValueError
        If the file does not contain a parallel model.

    Warnings
    --------
    Loads with `weights_only=False` (unpickles arbitrary objects); only
    call on trusted files.
    """
    return load_full_model(cls, path, return_metadata, map_location, trusted=trusted)

parallel_esn

parallel_esn(
    input_dim: int,
    core_width: int,
    halo: int,
    reservoir_size: int = 500,
    *,
    topology: TopologySpec | None = None,
    spectral_radius: float = 0.6,
    leak_rate: float = 1.0,
    input_scaling: float = 0.1,
    feedback_initializer: InitializerSpec | None = None,
    activation: str = "tanh",
    bias: bool = True,
    trainable: bool = False,
    seed: Any = None,
    readout: ReadoutSpec = "ridge",
    readout_alpha: float = 0.0001,
    readout_bias: bool = True,
    readout_name: str = "output",
    readout_kwargs: dict[str, Any] | None = None,
    **reservoir_kwargs: Any
) -> ParallelESNModel

Build a parallel local-state reservoir (Pathak et al. 2018).

Splits a spatially-extended field of dimension input_dim into P = input_dim / core_width overlapping patches (core width core_width, halo halo on each side, periodic boundaries), all sharing one reservoir (advanced batched over patches) and one weight-tied readout (core width core_width). See ParallelESNModel and the module docstring for the full architecture and the forecasting loop.

The defaults (spectral_radius=0.6, input_scaling=0.1, readout_alpha=1e-4) are tuned for the local-patch regime, which uses a smaller, better-conditioned reservoir per patch than a single global ESN — the classic Pathak KS settings. input_scaling=0.1 in particular is decisive: the per-patch input width (core_width + 2*halo) is large enough that an unscaled uniform(-1, 1) input map drives tanh deep into saturation, collapsing the reservoir's memory; scaling the input weights down keeps the dynamics responsive (on the canonical L=22 KS field it is the difference between a fraction of a Lyapunov time and ~4 Lyapunov times of valid prediction).

PARAMETER DESCRIPTION
input_dim

Full spatial dimension D of the field (e.g. the KS grid size).

TYPE: int

core_width

Core width w each patch predicts. Must divide input_dim.

TYPE: int

halo

Halo width g — neighbouring cells read on each side of the core (periodic). The per-patch reservoir input width is core_width + 2 * halo.

TYPE: int

reservoir_size

Number of units N in the shared reservoir (per patch).

TYPE: int DEFAULT: 500

topology

Topology for the recurrent weights. Accepts a registry name, a (name, params) tuple, a callable, or a configured resdag.init.topology.TopologyInitializer.

TYPE: TopologySpec DEFAULT: None

spectral_radius

Target spectral radius for the recurrent weights.

TYPE: float DEFAULT: 0.6

leak_rate

Leaky-integration rate (1.0 = no leak).

TYPE: float DEFAULT: 1.0

input_scaling

Scale of the per-patch input (feedback) weights when feedback_initializer is left at its default. The weights are drawn from uniform(-input_scaling, input_scaling) (via the "random" initializer), keeping the tanh reservoir out of saturation on a wide per-patch input. Ignored when an explicit feedback_initializer is supplied (it then owns the input-weight scale).

TYPE: float DEFAULT: 0.1

feedback_initializer

Initializer for the per-patch input weights. Same accepted forms as topology. When given, it overrides input_scaling. Left at its default (None), the factory uses ("random", {"input_scaling": input_scaling}).

TYPE: InitializerSpec DEFAULT: None

activation

Activation function ("tanh", "relu", "sigmoid", "identity").

TYPE: str DEFAULT: "tanh"

bias

Whether the reservoir uses a bias term.

TYPE: bool DEFAULT: True

trainable

Whether the reservoir weights are trainable.

TYPE: bool DEFAULT: False

seed

Reproducibility seed fixing every reservoir parameter.

TYPE: int or Generator DEFAULT: None

readout

A built-in readout name or a ReadoutLayer subclass, with the same solver choices as resdag.models.classic_esn.

TYPE: str or type[ReadoutLayer] DEFAULT: "ridge"

readout_alpha

Ridge regularization for the readout.

TYPE: float DEFAULT: 1e-4

readout_bias

Whether the readout uses a bias term.

TYPE: bool DEFAULT: True

readout_name

Name for the readout layer.

TYPE: str DEFAULT: "output"

readout_kwargs

Additional readout constructor options. Architecture widths are fixed.

TYPE: dict DEFAULT: None

**reservoir_kwargs

Additional keyword arguments forwarded to resdag.layers.ESNLayer (e.g. sparse, noise, input_initializer).

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION
ParallelESNModel

The assembled parallel reservoir, ready for ParallelESNModel.fit and ParallelESNModel.forecast.

RAISES DESCRIPTION
ValueError

If core_width does not divide input_dim, or if a size argument is out of range.

Examples:

Forecast a Kuramoto-Sivashinsky field with local patches::

>>> import torch
>>> from resdag import kuramoto_sivashinsky
>>> from resdag.models import parallel_esn
>>> data = kuramoto_sivashinsky(3000, n_grid=64, dtype=torch.float64)
>>> model = parallel_esn(input_dim=64, core_width=4, halo=6, reservoir_size=400,
...                      seed=0)
>>> warmup, train = data[:, :200], data[:, 200:2200]
>>> model.fit(warmup, train[:, :-1], train[:, 1:])
>>> pred = model.forecast(train[:, -100:], horizon=400)
See Also

ParallelESNModel : The model class this factory builds. resdag.datasets.kuramoto_sivashinsky : The canonical spatiotemporal benchmark. resdag.models.classic_esn : Single global reservoir baseline.

Source code in src/resdag/models/parallel_esn.py
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
def parallel_esn(
    input_dim: int,
    core_width: int,
    halo: int,
    reservoir_size: int = 500,
    *,
    # Reservoir params
    topology: TopologySpec | None = None,
    spectral_radius: float = 0.6,
    leak_rate: float = 1.0,
    input_scaling: float = 0.1,
    feedback_initializer: InitializerSpec | None = None,
    activation: str = "tanh",
    bias: bool = True,
    trainable: bool = False,
    seed: Any = None,
    # Readout params
    readout: ReadoutSpec = "ridge",
    readout_alpha: float = 1e-4,
    readout_bias: bool = True,
    readout_name: str = "output",
    readout_kwargs: dict[str, Any] | None = None,
    # Extra reservoir kwargs
    **reservoir_kwargs: Any,
) -> ParallelESNModel:
    r"""Build a parallel local-state reservoir (Pathak et al. 2018).

    Splits a spatially-extended field of dimension `input_dim` into `P = input_dim / core_width` overlapping patches (core width `core_width`, halo
    `halo` on each side, periodic boundaries), all sharing **one** reservoir
    (advanced batched over patches) and **one** weight-tied readout (core width
    `core_width`).  See `ParallelESNModel` and the module docstring for
    the full architecture and the forecasting loop.

    The defaults (`spectral_radius=0.6`, `input_scaling=0.1`,
    `readout_alpha=1e-4`) are tuned for the local-patch regime, which uses a
    smaller, better-conditioned reservoir per patch than a single global ESN —
    the classic Pathak KS settings.  `input_scaling=0.1` in particular is
    decisive: the per-patch input width (`core_width + 2*halo`) is large enough
    that an unscaled `uniform(-1, 1)` input map drives `tanh` deep into
    saturation, collapsing the reservoir's memory; scaling the input weights down
    keeps the dynamics responsive (on the canonical L=22 KS field it is the
    difference between a fraction of a Lyapunov time and ~4 Lyapunov times of
    valid prediction).

    Parameters
    ----------
    input_dim : int
        Full spatial dimension `D` of the field (e.g. the KS grid size).
    core_width : int
        Core width `w` each patch predicts.  Must divide `input_dim`.
    halo : int
        Halo width `g` — neighbouring cells read on each side of the core
        (periodic).  The per-patch reservoir input width is `core_width + 2 * halo`.
    reservoir_size : int, default=500
        Number of units `N` in the shared reservoir (per patch).
    topology : TopologySpec, optional
        Topology for the recurrent weights.  Accepts a registry name, a
        `(name, params)` tuple, a callable, or a configured
        `resdag.init.topology.TopologyInitializer`.
    spectral_radius : float, default=0.6
        Target spectral radius for the recurrent weights.
    leak_rate : float, default=1.0
        Leaky-integration rate (1.0 = no leak).
    input_scaling : float, default=0.1
        Scale of the per-patch input (feedback) weights when
        `feedback_initializer` is left at its default.  The weights are drawn
        from `uniform(-input_scaling, input_scaling)` (via the `"random"`
        initializer), keeping the `tanh` reservoir out of saturation on a
        wide per-patch input.  Ignored when an explicit `feedback_initializer`
        is supplied (it then owns the input-weight scale).
    feedback_initializer : InitializerSpec, optional
        Initializer for the per-patch input weights.  Same accepted forms as
        `topology`.  When given, it overrides `input_scaling`.  Left at its
        default (`None`), the factory uses `("random", {"input_scaling": input_scaling})`.
    activation : str, default="tanh"
        Activation function (`"tanh"`, `"relu"`, `"sigmoid"`,
        `"identity"`).
    bias : bool, default=True
        Whether the reservoir uses a bias term.
    trainable : bool, default=False
        Whether the reservoir weights are trainable.
    seed : int or torch.Generator, optional
        Reproducibility seed fixing every reservoir parameter.
    readout : str or type[ReadoutLayer], default="ridge"
        A built-in readout name or a ReadoutLayer subclass, with the same
        solver choices as `resdag.models.classic_esn`.
    readout_alpha : float, default=1e-4
        Ridge regularization for the readout.
    readout_bias : bool, default=True
        Whether the readout uses a bias term.
    readout_name : str, default="output"
        Name for the readout layer.
    readout_kwargs : dict, optional
        Additional readout constructor options. Architecture widths are fixed.
    **reservoir_kwargs : Any
        Additional keyword arguments forwarded to `resdag.layers.ESNLayer`
        (e.g. `sparse`, `noise`, `input_initializer`).

    Returns
    -------
    ParallelESNModel
        The assembled parallel reservoir, ready for `ParallelESNModel.fit`
        and `ParallelESNModel.forecast`.

    Raises
    ------
    ValueError
        If `core_width` does not divide `input_dim`, or if a size argument is
        out of range.

    Examples
    --------
    Forecast a Kuramoto-Sivashinsky field with local patches::

    >>> import torch
    >>> from resdag import kuramoto_sivashinsky
    >>> from resdag.models import parallel_esn
    >>> data = kuramoto_sivashinsky(3000, n_grid=64, dtype=torch.float64)
    >>> model = parallel_esn(input_dim=64, core_width=4, halo=6, reservoir_size=400,
    ...                      seed=0)
    >>> warmup, train = data[:, :200], data[:, 200:2200]
    >>> model.fit(warmup, train[:, :-1], train[:, 1:])   # doctest: +SKIP
    >>> pred = model.forecast(train[:, -100:], horizon=400)  # doctest: +SKIP

    See Also
    --------
    ParallelESNModel : The model class this factory builds.
    resdag.datasets.kuramoto_sivashinsky : The canonical spatiotemporal benchmark.
    resdag.models.classic_esn : Single global reservoir baseline.
    """
    _patch_gather_index(input_dim, core_width, halo)
    patch_width = core_width + 2 * halo

    # Default the per-patch input map to a *scaled* random init: on a wide
    # per-patch input an unscaled ``uniform(-1, 1)`` saturates the tanh
    # reservoir (see the ``input_scaling`` docstring).  An explicit
    # ``feedback_initializer`` overrides this and owns the input-weight scale.
    if feedback_initializer is None:
        feedback_initializer = ("random", {"input_scaling": input_scaling})

    reservoir = ESNLayer(
        reservoir_size=reservoir_size,
        feedback_size=patch_width,
        topology=topology,
        spectral_radius=spectral_radius,
        leak_rate=leak_rate,
        feedback_initializer=feedback_initializer,
        activation=activation,
        bias=bias,
        trainable=trainable,
        seed=seed,
        **reservoir_kwargs,
    )

    readout_layer = _make_readout(
        readout,
        in_features=reservoir_size,
        out_features=core_width,
        bias=readout_bias,
        alpha=readout_alpha,
        name=readout_name,
        readout_kwargs=readout_kwargs,
    ).to(device=reservoir.weight_hh.device, dtype=reservoir.weight_hh.dtype)

    return ParallelESNModel(
        reservoir=reservoir,
        readout=readout_layer,
        input_dim=input_dim,
        core_width=core_width,
        halo=halo,
    )

power_augmented

power_augmented(
    reservoir_size: int,
    feedback_size: int,
    output_size: int,
    exponent: float = 3.0,
    input_size: int | None = None,
    input_initializer: InitializerSpec | None = None,
    topology: TopologySpec | None = None,
    spectral_radius: float = 0.9,
    leak_rate: float = 1.0,
    feedback_initializer: InitializerSpec | None = None,
    activation: str = "tanh",
    bias: bool = True,
    trainable: bool = False,
    readout: ReadoutSpec = "ridge",
    readout_alpha: float = 1e-06,
    readout_bias: bool = True,
    readout_name: str = "output",
    readout_kwargs: dict[str, Any] | None = None,
    **reservoir_kwargs: Any
) -> ESNModel

Build Power Augmented ESN model.

This model augments reservoir states by exponentiating to a power and concatenating with input. This augmentation helps capture higher-order dynamics in chaotic systems.

Architecture:

Input -> Reservoir -> Power -> Concatenate(Input, Augmented) -> Readout
PARAMETER DESCRIPTION
reservoir_size

Number of units in the reservoir.

TYPE: int

feedback_size

Dimension of feedback signal (input features).

TYPE: int

output_size

Dimension of output signal.

TYPE: int

exponent

Exponent applied to every reservoir state. Tanh reservoir states live in [-1, 1] and routinely include negative and zero values, so the exponent must be chosen with that signed range in mind (see Notes). The default 3.0 is an odd integer and therefore sign-preserving; an even exponent such as 2.0 maps every state to a non-negative value and so discards the sign of the reservoir activations.

TYPE: float DEFAULT: 3.0

input_size

Dimension of an optional driving (exogenous) input. When given, the model takes two inputs (feedback, driver) and the driver feeds the reservoir alongside the autoregressive feedback. The driver is kept out of the input concatenation, so the readout in_features stays feedback_size + reservoir_size. None (default) builds a feedback-only model, unchanged from previous behavior.

TYPE: int or None DEFAULT: None

input_initializer

Initializer for the driving-input weights. Same format as feedback_initializer. Only used when input_size is given.

TYPE: str, tuple, or InputFeedbackInitializer DEFAULT: None

topology

Topology for recurrent weights. Accepts:

  • str: Registry name (e.g., "erdos_renyi")
  • tuple: (name, params) like ("watts_strogatz", {"k": 6, "p": 0.1})
  • TopologyInitializer: Pre-configured object

TYPE: str, tuple, or TopologyInitializer DEFAULT: None

spectral_radius

Target spectral radius for recurrent weights.

TYPE: float DEFAULT: 0.9

leak_rate

Leaky integration rate. 1.0 = no leaking (standard ESN).

TYPE: float DEFAULT: 1.0

feedback_initializer

Initializer for feedback weights. Same format as topology.

TYPE: str, tuple, or InputFeedbackInitializer DEFAULT: None

activation

Activation function for reservoir neurons.

TYPE: (tanh, relu, sigmoid, identity) DEFAULT: 'tanh'

bias

Whether to include bias in reservoir.

TYPE: bool DEFAULT: True

trainable

If True, reservoir weights are trainable via backpropagation.

TYPE: bool DEFAULT: False

readout

A built-in name ("ridge", "cholesky", "cg", "svd", "pinv", "incremental", "rls", "fista", "lsmr") or a resdag.layers.readouts.ReadoutLayer subclass. Additional solver options go in readout_kwargs.

TYPE: str or type[ReadoutLayer] DEFAULT: "ridge"

readout_alpha

L2 regularization strength for ridge regression in readout.

TYPE: float DEFAULT: 1e-6

readout_bias

Whether to include bias in readout layer.

TYPE: bool DEFAULT: True

readout_name

Name for the readout layer. Used as target key in training.

TYPE: str DEFAULT: 'output'

readout_kwargs

Extra readout constructor options, including trainable, rcond, state_noise or gram_dtype. Architecture widths are fixed.

TYPE: dict DEFAULT: None

**reservoir_kwargs

Additional keyword arguments passed to ESNLayer.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION
ESNModel

Configured Power Augmented ESN model ready for training and inference.

Notes

The augmentation applies resdag.layers.Power to the raw reservoir states, which for a tanh activation lie in [-1, 1] — negatives and zeros included. Choose exponent accordingly:

  • Even integers (2.0, 4.0, …) are always safe: every state maps to a non-negative value with no nan/inf.
  • Odd integers (3.0, 5.0, …) are safe and sign-preserving: negative states stay negative.
  • Non-integer exponents (e.g. 0.5, 1.5) applied to a negative state produce nan under the default torch.pow, silently corrupting the readout inputs. Negative exponents (e.g. -1.0) produce inf on the zeros that tanh states pass through.

If you need a non-integer exponent on signed states, wire the model by hand with Power(exponent, sign_preserving=True), which applies sign(x) * abs(x) ** exponent and stays finite for negative bases. This factory always uses the default (non-sign-preserving) Power to keep the well-established integer-exponent behaviour unchanged.

Examples:

Basic usage:

>>> from resdag.models import power_augmented
>>> model = power_augmented(
...     reservoir_size=500,
...     feedback_size=3,
...     output_size=3,
...     exponent=3.0,
... )
>>> model.summary()

With custom topology:

>>> from resdag.init.topology import get_topology
>>> model = power_augmented(
...     reservoir_size=500,
...     feedback_size=3,
...     output_size=3,
...     topology=get_topology("watts_strogatz", k=4, p=0.3),
...     spectral_radius=0.95,
...     exponent=3.0,
... )

Training and forecasting:

>>> from resdag.training import ESNTrainer
>>> trainer = ESNTrainer(model)
>>> trainer.fit(
...     warmup_inputs=(warmup,),
...     train_inputs=(train,),
...     targets={"output": target},
... )
>>> predictions = model.forecast(forecast_warmup, horizon=100)
See Also

classic_esn : Traditional ESN without state augmentation. resdag.training.ESNTrainer : Trainer for fitting readout. resdag.init.topology.get_topology : Get topology by name.

Source code in src/resdag/models/power_augmented.py
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 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
 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
def power_augmented(
    reservoir_size: int,
    feedback_size: int,
    output_size: int,
    exponent: float = 3.0,
    input_size: int | None = None,
    input_initializer: InitializerSpec | None = None,
    # Reservoir params
    topology: TopologySpec | None = None,
    spectral_radius: float = 0.9,
    leak_rate: float = 1.0,
    feedback_initializer: InitializerSpec | None = None,
    activation: str = "tanh",
    bias: bool = True,
    trainable: bool = False,
    # Readout params
    readout: ReadoutSpec = "ridge",
    readout_alpha: float = 1e-6,
    readout_bias: bool = True,
    readout_name: str = "output",
    readout_kwargs: dict[str, Any] | None = None,
    # Extra reservoir kwargs
    **reservoir_kwargs: Any,
) -> ESNModel:
    """
    Build Power Augmented ESN model.

    This model augments reservoir states by exponentiating to a power and concatenating with input.
    This augmentation helps capture higher-order dynamics in chaotic systems.

    Architecture:

    ```text
    Input -> Reservoir -> Power -> Concatenate(Input, Augmented) -> Readout
    ```

    Parameters
    ----------
    reservoir_size : int
        Number of units in the reservoir.
    feedback_size : int
        Dimension of feedback signal (input features).
    output_size : int
        Dimension of output signal.
    exponent : float, default=3.0
        Exponent applied to **every** reservoir state. Tanh reservoir states
        live in `[-1, 1]` and routinely include negative and zero values, so
        the exponent must be chosen with that signed range in mind (see Notes).
        The default `3.0` is an odd integer and therefore *sign-preserving*;
        an even exponent such as `2.0` maps every state to a non-negative
        value and so discards the sign of the reservoir activations.
    input_size : int or None, optional
        Dimension of an optional driving (exogenous) input.  When given, the
        model takes two inputs `(feedback, driver)` and the driver feeds the
        reservoir alongside the autoregressive feedback.  The driver is kept out
        of the input concatenation, so the readout `in_features` stays
        `feedback_size + reservoir_size`.  `None` (default) builds a
        feedback-only model, unchanged from previous behavior.
    input_initializer : str, tuple, or InputFeedbackInitializer, optional
        Initializer for the driving-input weights.  Same format as
        `feedback_initializer`.  Only used when `input_size` is given.
    topology : str, tuple, or TopologyInitializer, optional
        Topology for recurrent weights. Accepts:

        - str: Registry name (e.g., `"erdos_renyi"`)
        - tuple: `(name, params)` like `("watts_strogatz", {"k": 6, "p": 0.1})`
        - TopologyInitializer: Pre-configured object

    spectral_radius : float, default=0.9
        Target spectral radius for recurrent weights.
    leak_rate : float, default=1.0
        Leaky integration rate. 1.0 = no leaking (standard ESN).
    feedback_initializer : str, tuple, or InputFeedbackInitializer, optional
        Initializer for feedback weights. Same format as `topology`.
    activation : {'tanh', 'relu', 'sigmoid', 'identity'}, default='tanh'
        Activation function for reservoir neurons.
    bias : bool, default=True
        Whether to include bias in reservoir.
    trainable : bool, default=False
        If True, reservoir weights are trainable via backpropagation.
    readout : str or type[ReadoutLayer], default="ridge"
        A built-in name (`"ridge"`, `"cholesky"`, `"cg"`, `"svd"`,
        `"pinv"`, `"incremental"`, `"rls"`, `"fista"`, `"lsmr"`) or a
        `resdag.layers.readouts.ReadoutLayer` subclass. Additional
        solver options go in `readout_kwargs`.
    readout_alpha : float, default=1e-6
        L2 regularization strength for ridge regression in readout.
    readout_bias : bool, default=True
        Whether to include bias in readout layer.
    readout_name : str, default='output'
        Name for the readout layer. Used as target key in training.
    readout_kwargs : dict, optional
        Extra readout constructor options, including `trainable`, `rcond`,
        `state_noise` or `gram_dtype`. Architecture widths are fixed.
    **reservoir_kwargs
        Additional keyword arguments passed to `ESNLayer`.

    Returns
    -------
    ESNModel
        Configured Power Augmented ESN model ready for training and inference.

    Notes
    -----
    The augmentation applies `resdag.layers.Power` to the raw reservoir
    states, which for a `tanh` activation lie in `[-1, 1]` — negatives and
    zeros included. Choose `exponent` accordingly:

    - **Even integers** (`2.0`, `4.0`, …) are always safe: every state maps
      to a non-negative value with no `nan`/`inf`.
    - **Odd integers** (`3.0`, `5.0`, …) are safe and *sign-preserving*:
      negative states stay negative.
    - **Non-integer exponents** (e.g. `0.5`, `1.5`) applied to a *negative*
      state produce `nan` under the default `torch.pow`, silently
      corrupting the readout inputs. **Negative exponents** (e.g. `-1.0`)
      produce `inf` on the zeros that `tanh` states pass through.

    If you need a non-integer exponent on signed states, wire the model by hand
    with `Power(exponent, sign_preserving=True)`, which applies
    `sign(x) * abs(x) ** exponent` and stays finite for negative bases. This
    factory always uses the default (non-sign-preserving) `Power` to keep the
    well-established integer-exponent behaviour unchanged.

    Examples
    --------
    Basic usage:

    >>> from resdag.models import power_augmented
    >>> model = power_augmented(
    ...     reservoir_size=500,
    ...     feedback_size=3,
    ...     output_size=3,
    ...     exponent=3.0,
    ... )
    >>> model.summary()

    With custom topology:

    >>> from resdag.init.topology import get_topology
    >>> model = power_augmented(
    ...     reservoir_size=500,
    ...     feedback_size=3,
    ...     output_size=3,
    ...     topology=get_topology("watts_strogatz", k=4, p=0.3),
    ...     spectral_radius=0.95,
    ...     exponent=3.0,
    ... )

    Training and forecasting:

    >>> from resdag.training import ESNTrainer
    >>> trainer = ESNTrainer(model)
    >>> trainer.fit(
    ...     warmup_inputs=(warmup,),
    ...     train_inputs=(train,),
    ...     targets={"output": target},
    ... )
    >>> predictions = model.forecast(forecast_warmup, horizon=100)

    See Also
    --------
    classic_esn : Traditional ESN without state augmentation.
    resdag.training.ESNTrainer : Trainer for fitting readout.
    resdag.init.topology.get_topology : Get topology by name.
    """
    # Power augmentation: raise reservoir states to ``exponent``, concat input.
    return _esn_builder(
        reservoir_size=reservoir_size,
        feedback_size=feedback_size,
        output_size=output_size,
        augment=lambda: Power(exponent=exponent),
        concat_input=True,
        input_size=input_size,
        input_initializer=input_initializer,
        topology=topology,
        spectral_radius=spectral_radius,
        leak_rate=leak_rate,
        feedback_initializer=feedback_initializer,
        activation=activation,
        bias=bias,
        trainable=trainable,
        readout=readout,
        readout_alpha=readout_alpha,
        readout_bias=readout_bias,
        readout_name=readout_name,
        readout_kwargs=readout_kwargs,
        **reservoir_kwargs,
    )

resesn

resesn(
    reservoir_size: int,
    feedback_size: int,
    output_size: int,
    alpha: float = 0.5,
    beta: float = 0.9,
    input_size: int | None = None,
    input_initializer: InitializerSpec | None = None,
    topology: TopologySpec | None = None,
    spectral_radius: float = 0.9,
    orthogonal_scaling: float = 1.0,
    feedback_initializer: InitializerSpec | None = None,
    activation: str = "tanh",
    bias: bool = True,
    trainable: bool = False,
    readout: ReadoutSpec = "ridge",
    readout_alpha: float = 1e-06,
    readout_bias: bool = True,
    readout_name: str = "output",
    readout_kwargs: dict[str, Any] | None = None,
    **reservoir_kwargs: Any
) -> ESNModel

Build a Residual Echo State Network (ResESN) model.

ResESN (Ceni & Gallicchio, 2024) generalises ES2N by decoupling the orthogonal-skip and nonlinear branch weights:

\[ x_t = \alpha\,O\,x_{t-1} + \beta\,\phi(W_r x_{t-1} + \cdots) \]

with independent coefficients \(\alpha\) (skip) and \(\beta\) (nonlinear) replacing the leak rate. \(\alpha = 1 - \beta\) recovers ES2N. This factory wires the same input-concatenation architecture as resdag.models.classic_esn:

Input -> ResESN Reservoir -> Concatenate(Input, Reservoir) -> Readout
PARAMETER DESCRIPTION
reservoir_size

Number of units in the reservoir.

TYPE: int

feedback_size

Number of feedback features (autoregressive input dimension).

TYPE: int

output_size

Number of output features.

TYPE: int

alpha

Scaling of the orthogonal skip (residual) branch.

TYPE: float DEFAULT: 0.5

beta

Scaling of the nonlinear branch.

TYPE: float DEFAULT: 0.9

input_size

Dimension of an optional driving (exogenous) input. When given, the model takes two inputs (feedback, driver); the driver is kept out of the input concatenation. None (default) builds a feedback-only model.

TYPE: int or None DEFAULT: None

input_initializer

Initializer for the driving-input weights. Only used when input_size is given.

TYPE: InitializerSpec DEFAULT: None

topology

Topology for the recurrent weights W_r. Accepts a registry name, a (name, params) tuple, a callable, or a pre-configured resdag.init.topology.TopologyInitializer.

TYPE: TopologySpec DEFAULT: None

spectral_radius

Target spectral radius for the recurrent weights W_r.

TYPE: float DEFAULT: 0.9

orthogonal_scaling

Gain on the orthogonal skip matrix O. 1.0 keeps it exactly norm-preserving.

TYPE: float DEFAULT: 1.0

feedback_initializer

Initializer for the feedback weights.

TYPE: InitializerSpec DEFAULT: None

activation

Activation for the nonlinear branch.

TYPE: (tanh, relu, sigmoid, identity) DEFAULT: 'tanh'

bias

Whether to use a bias in the reservoir.

TYPE: bool DEFAULT: True

trainable

Whether the reservoir weights are trainable. The orthogonal skip stays frozen regardless.

TYPE: bool DEFAULT: False

readout

A built-in name ("ridge", "cholesky", "cg", "svd", "pinv", "incremental", "rls", "fista", "lsmr") or a resdag.layers.readouts.ReadoutLayer subclass. Additional solver options go in readout_kwargs.

TYPE: str or type[ReadoutLayer] DEFAULT: "ridge"

readout_alpha

Ridge regularization for the readout.

TYPE: float DEFAULT: 1e-6

readout_bias

Whether to use a bias in the readout.

TYPE: bool DEFAULT: True

readout_name

Name for the readout layer (used as the target key in training).

TYPE: str DEFAULT: "output"

readout_kwargs

Extra readout options, such as trainable=True, solver, state_noise or gram_dtype. Architecture dimensions are fixed.

TYPE: dict DEFAULT: None

**reservoir_kwargs

Additional keyword arguments forwarded to resdag.layers.reservoirs.resesn.ResESNLayer (e.g. bias_scaling, seed).

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION
`resdag.core.ESNModel`

Configured ResESN model ready for training and inference.

Examples:

>>> from resdag.models import resesn
>>> model = resesn(500, feedback_size=3, output_size=3, alpha=0.6, beta=0.4)
See Also

resdag.models.es2n : Edge-of-Stability State Network (convex combination). resdag.models.classic_esn : Traditional leaky ESN. resdag.layers.reservoirs.resesn.ResESNLayer : The reservoir layer.

Source code in src/resdag/models/resesn.py
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 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
 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
def resesn(
    reservoir_size: int,
    feedback_size: int,
    output_size: int,
    alpha: float = 0.5,
    beta: float = 0.9,
    input_size: int | None = None,
    input_initializer: InitializerSpec | None = None,
    # Reservoir params
    topology: TopologySpec | None = None,
    spectral_radius: float = 0.9,
    orthogonal_scaling: float = 1.0,
    feedback_initializer: InitializerSpec | None = None,
    activation: str = "tanh",
    bias: bool = True,
    trainable: bool = False,
    # Readout params
    readout: ReadoutSpec = "ridge",
    readout_alpha: float = 1e-6,
    readout_bias: bool = True,
    readout_name: str = "output",
    readout_kwargs: dict[str, Any] | None = None,
    # Extra reservoir kwargs
    **reservoir_kwargs: Any,
) -> ESNModel:
    r"""Build a Residual Echo State Network (ResESN) model.

    ResESN (Ceni & Gallicchio, 2024) generalises ES2N by **decoupling** the
    orthogonal-skip and nonlinear branch weights:

    $$
    x_t = \alpha\,O\,x_{t-1} + \beta\,\phi(W_r x_{t-1} + \cdots)
    $$

    with independent coefficients $\alpha$ (skip) and $\beta$
    (nonlinear) replacing the leak rate.  $\alpha = 1 - \beta$ recovers
    ES2N.  This factory wires the same input-concatenation architecture as
    `resdag.models.classic_esn`:

    ```text
    Input -> ResESN Reservoir -> Concatenate(Input, Reservoir) -> Readout
    ```

    Parameters
    ----------
    reservoir_size : int
        Number of units in the reservoir.
    feedback_size : int
        Number of feedback features (autoregressive input dimension).
    output_size : int
        Number of output features.
    alpha : float, default=0.5
        Scaling of the orthogonal skip (residual) branch.
    beta : float, default=0.9
        Scaling of the nonlinear branch.
    input_size : int or None, optional
        Dimension of an optional driving (exogenous) input.  When given, the
        model takes two inputs `(feedback, driver)`; the driver is kept out of
        the input concatenation.  `None` (default) builds a feedback-only
        model.
    input_initializer : InitializerSpec, optional
        Initializer for the driving-input weights.  Only used when
        `input_size` is given.
    topology : TopologySpec, optional
        Topology for the recurrent weights `W_r`.  Accepts a registry name, a
        `(name, params)` tuple, a callable, or a pre-configured
        `resdag.init.topology.TopologyInitializer`.
    spectral_radius : float, default=0.9
        Target spectral radius for the recurrent weights `W_r`.
    orthogonal_scaling : float, default=1.0
        Gain on the orthogonal skip matrix `O`.  `1.0` keeps it exactly
        norm-preserving.
    feedback_initializer : InitializerSpec, optional
        Initializer for the feedback weights.
    activation : {'tanh', 'relu', 'sigmoid', 'identity'}, default='tanh'
        Activation for the nonlinear branch.
    bias : bool, default=True
        Whether to use a bias in the reservoir.
    trainable : bool, default=False
        Whether the reservoir weights are trainable.  The orthogonal skip stays
        frozen regardless.
    readout : str or type[ReadoutLayer], default="ridge"
        A built-in name (`"ridge"`, `"cholesky"`, `"cg"`, `"svd"`,
        `"pinv"`, `"incremental"`, `"rls"`, `"fista"`, `"lsmr"`) or a
        `resdag.layers.readouts.ReadoutLayer` subclass. Additional
        solver options go in `readout_kwargs`.
    readout_alpha : float, default=1e-6
        Ridge regularization for the readout.
    readout_bias : bool, default=True
        Whether to use a bias in the readout.
    readout_name : str, default="output"
        Name for the readout layer (used as the target key in training).
    readout_kwargs : dict, optional
        Extra readout options, such as `trainable=True`, `solver`,
        `state_noise` or `gram_dtype`. Architecture dimensions are fixed.
    **reservoir_kwargs : Any
        Additional keyword arguments forwarded to
        `resdag.layers.reservoirs.resesn.ResESNLayer` (e.g.
        `bias_scaling`, `seed`).

    Returns
    -------
    `resdag.core.ESNModel`
        Configured ResESN model ready for training and inference.

    Examples
    --------
    >>> from resdag.models import resesn
    >>> model = resesn(500, feedback_size=3, output_size=3, alpha=0.6, beta=0.4)

    See Also
    --------
    resdag.models.es2n : Edge-of-Stability State Network (convex combination).
    resdag.models.classic_esn : Traditional leaky ESN.
    resdag.layers.reservoirs.resesn.ResESNLayer : The reservoir layer.
    """
    return _esn_builder(
        reservoir_size=reservoir_size,
        feedback_size=feedback_size,
        output_size=output_size,
        augment=None,
        concat_input=True,
        input_size=input_size,
        input_initializer=input_initializer,
        reservoir_cls=ResESNLayer,
        topology=topology,
        spectral_radius=spectral_radius,
        feedback_initializer=feedback_initializer,
        activation=activation,
        bias=bias,
        trainable=trainable,
        readout=readout,
        readout_alpha=readout_alpha,
        readout_bias=readout_bias,
        readout_name=readout_name,
        readout_kwargs=readout_kwargs,
        alpha=alpha,
        beta=beta,
        orthogonal_scaling=orthogonal_scaling,
        **reservoir_kwargs,
    )

ensemble

Ensemble Reservoir Computing Models

This module provides ensemble wrappers for groups of independently-trained resdag.core.ESNModel instances.

CLASS DESCRIPTION
CoupledEnsembleESNModel

N independent ESN sub-models whose autoregressive forecasts are coupled through a shared averaged feedback signal at every timestep.

See Also

resdag.models.coupled_ensemble_esn : Factory function for quick construction.

CoupledEnsembleESNModel

CoupledEnsembleESNModel(models: list[ESNModel], aggregator: str | Module = 'mean')

Bases: Module

Ensemble of N independently-trained ESN models with coupled feedback.

Each sub-model is a complete resdag.core.ESNModel built via the pytorch_symbolic API. The models are trained independently but coupled during forecasting: at every autoregressive step every model receives the same aggregated output (e.g. the mean across models) as its next feedback input.

PARAMETER DESCRIPTION
models

N pre-built ESN sub-models. Diversity comes from their independent random reservoir initialization.

TYPE: list of ESNModel

aggregator

How to combine the N per-model outputs into a single feedback tensor.

  • "mean" — arithmetic mean across models.
  • "median" — interpolated (statistical) median across models; for an even number of models the two central values are averaged.
  • Any nn.Module that accepts a stacked tensor of shape (N, batch, timesteps, features) and returns (batch, timesteps, features). E.g. resdag.ensemble.aggregators.OutliersFilteredMean.

TYPE: str or Module DEFAULT: `"mean"`

Examples:

Typical use via the factory:

>>> from resdag.models import coupled_ensemble_esn
>>> ensemble = coupled_ensemble_esn(n_models=5, reservoir_size=300,
...                                feedback_size=3, output_size=3)
>>> ensemble.fit((warmup,), (train,), {"output": targets})
>>> ensemble.reset_reservoirs()
>>> preds = ensemble.forecast(forecast_warmup, horizon=200)
>>> preds.shape
torch.Size([1, 200, 3])

With a custom aggregator:

>>> from resdag.ensemble.aggregators import OutliersFilteredMean
>>> ensemble = coupled_ensemble_esn(
...     n_models=10, reservoir_size=300, feedback_size=3, output_size=3,
...     aggregate=OutliersFilteredMean(method="z_score", threshold=2.0),
... )
See Also

resdag.models.coupled_ensemble_esn : Convenience factory function. resdag.ensemble.aggregators.OutliersFilteredMean : Outlier-robust aggregation layer.

PARAMETER DESCRIPTION
models

Sub-models. Must be non-empty.

TYPE: list of ESNModel

aggregator

Aggregation strategy. See class docstring for options.

TYPE: str or Module DEFAULT: `"mean"`

RAISES DESCRIPTION
ValueError

If models is empty, if aggregator is an unknown string, if any sub-model is multi-output (multi-head), or if any sub-model's output dimension does not match its feedback (first input) dimension. Multi-output sub-models are rejected because the ensemble aggregates the members into a single shared feedback signal and has no meaningful coupled aggregation for auxiliary heads. The dimension check rejects headless / linear sub-models, whose output is the raw reservoir state rather than a feedback-dimensioned readout, since the coupled autoregressive loop feeds the aggregated output back as the next feedback input.

Source code in src/resdag/ensemble/coupled.py
 91
 92
 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
def __init__(
    self,
    models: list[ESNModel],
    aggregator: str | nn.Module = "mean",
) -> None:
    """Initialize the coupled ensemble.

    Parameters
    ----------
    models : list of ESNModel
        Sub-models.  Must be non-empty.
    aggregator : str or nn.Module, default `"mean"`
        Aggregation strategy.  See class docstring for options.

    Raises
    ------
    ValueError
        If `models` is empty, if `aggregator` is an unknown string, if
        any sub-model is multi-output (multi-head), or if any sub-model's
        output dimension does not match its feedback (first input)
        dimension.  Multi-output sub-models are rejected because the
        ensemble aggregates the members into a single shared feedback signal
        and has no meaningful coupled aggregation for auxiliary heads.  The
        dimension check rejects headless / linear sub-models, whose output is
        the raw reservoir state rather than a feedback-dimensioned readout,
        since the coupled autoregressive loop feeds the aggregated output
        back as the next feedback input.
    """
    super().__init__()
    if len(models) == 0:
        raise ValueError("CoupledEnsembleESNModel requires at least one sub-model.")
    if isinstance(aggregator, str) and aggregator not in ("mean", "median"):
        raise ValueError(
            f"aggregator must be 'mean', 'median', or an nn.Module; got '{aggregator}'."
        )

    if not isinstance(aggregator, (str, nn.Module)):
        raise TypeError("aggregator must be 'mean', 'median', or an nn.Module")
    for index, model in enumerate(models):
        if not isinstance(model, ESNModel):
            raise TypeError(
                f"Sub-model {index} must be an ESNModel, got {type(model).__name__}"
            )
    self._validate_feedback_output_dims(models)
    self._validate_member_interfaces(models)

    reservoir_owners: dict[int, int] = {}
    for index, model in enumerate(models):
        for layer in model.modules():
            if isinstance(layer, BaseReservoirLayer):
                owner = reservoir_owners.get(id(layer))
                if owner is not None:
                    raise ValueError(
                        f"Ensemble members {owner} and {index} share a reservoir layer instance. "
                        "Members require independent recurrent state. Use distinct reservoir "
                        "layer instances; their parameter tensors may still share weights."
                    )
                reservoir_owners[id(layer)] = index

    self.models = nn.ModuleList(models)

    if isinstance(aggregator, nn.Module):
        self.aggregator_module: nn.Module | None = aggregator
        self._aggregator_str: str | None = None
    else:
        self.aggregator_module = None
        self._aggregator_str = aggregator

n_models property

n_models: int

Number of sub-models in the ensemble.

forward

forward(*inputs: Tensor) -> Tensor

Run all sub-models on the same inputs and return the aggregated output.

PARAMETER DESCRIPTION
*inputs

Same input tensors passed to every sub-model.

TYPE: Tensor DEFAULT: ()

RETURNS DESCRIPTION
Tensor

Aggregated output of shape (batch, timesteps, output_size).

Source code in src/resdag/ensemble/coupled.py
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
def forward(self, *inputs: torch.Tensor) -> torch.Tensor:
    """Run all sub-models on the same inputs and return the aggregated output.

    Parameters
    ----------
    *inputs : torch.Tensor
        Same input tensors passed to every sub-model.

    Returns
    -------
    torch.Tensor
        Aggregated output of shape `(batch, timesteps, output_size)`.
    """
    outputs = [model(*inputs) for model in self.models]
    return self._aggregate(outputs)

forward_stateless

forward_stateless(
    *inputs: Tensor, states: Mapping[str, Tensor] | None = None, compile: bool = False
) -> tuple[Tensor, ReservoirStates]

Aggregate complete member predictions with explicit recurrent state.

Omitted states start every member from zero. Otherwise use the named dictionary returned by this method, whose keys are models.<member index>.<reservoir name>. The model's stored states remain untouched; returned states retain gradients across chunks.

Source code in src/resdag/ensemble/coupled.py
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
def forward_stateless(
    self,
    *inputs: torch.Tensor,
    states: Mapping[str, torch.Tensor] | None = None,
    compile: bool = False,
) -> tuple[torch.Tensor, ReservoirStates]:
    """Aggregate complete member predictions with explicit recurrent state.

    Omitted states start every member from zero. Otherwise use the named
    dictionary returned by this method, whose keys are
    `models.<member index>.<reservoir name>`. The model's stored states
    remain untouched; returned states retain gradients across chunks.
    """
    names = {
        f"models.{index}.{name}"
        for index, model in enumerate(self._iter_models())
        for name in model._get_execution_plan().reservoir_names
    }
    if states is not None and set(states) != names:
        raise ValueError(
            "Reservoir state keys must match the model; "
            f"missing={sorted(names - set(states))}, "
            f"unexpected={sorted(set(states) - names)}"
        )
    from resdag.core._hooks import call_with_states, has_execution_hooks, state_paths

    if has_execution_hooks(self):
        paths = state_paths(self)
        if set(paths) != names:
            raise ValueError(
                "Explicit-state execution cannot thread hidden aggregator reservoirs"
            )
        return cast(
            tuple[torch.Tensor, ReservoirStates],
            call_with_states(self, inputs, states, paths, compile=compile),
        )
    outputs = []
    final: ReservoirStates = {}
    for index, model in enumerate(self._iter_models()):
        prefix = f"models.{index}."
        member_states = (
            None
            if states is None
            else {
                key.removeprefix(prefix): value
                for key, value in states.items()
                if key.startswith(prefix)
            }
        )
        output, member_final = model.forward_stateless(
            *inputs, states=member_states, compile=compile
        )
        outputs.append(cast(torch.Tensor, output))
        final.update({prefix + key: value for key, value in member_final.items()})
    return self._aggregate(outputs), final

as_module

as_module(*, stateful: bool = False) -> ReservoirModelModule

Share all trained members and their aggregator with a PyTorch pipeline.

Source code in src/resdag/ensemble/coupled.py
366
367
368
369
370
371
372
373
def as_module(self, *, stateful: bool = False) -> ReservoirModelModule:
    """Share all trained members and their aggregator with a PyTorch pipeline."""
    for model in self._iter_models():
        if stateful:
            _validate_unique_reservoir_invocations(model)
        else:
            model._get_execution_plan()
    return ReservoirModelModule(self, stateful=stateful)

warmup

warmup(*inputs: Tensor) -> None

Teacher-forced warmup: synchronize every sub-model's reservoir state.

PARAMETER DESCRIPTION
*inputs

Warmup sequences. Passed identically to each sub-model.

TYPE: Tensor DEFAULT: ()

Source code in src/resdag/ensemble/coupled.py
375
376
377
378
379
380
381
382
383
384
385
@torch.no_grad()
def warmup(self, *inputs: torch.Tensor) -> None:
    """Teacher-forced warmup: synchronize every sub-model's reservoir state.

    Parameters
    ----------
    *inputs : torch.Tensor
        Warmup sequences.  Passed identically to each sub-model.
    """
    for model in self._iter_models():
        model.warmup(*inputs)

reset_reservoirs

reset_reservoirs() -> None

Reset reservoir states in all sub-models to zero / None.

Source code in src/resdag/ensemble/coupled.py
391
392
393
394
def reset_reservoirs(self) -> None:
    """Reset reservoir states in all sub-models to zero / None."""
    for model in self._iter_models():
        model.reset_reservoirs()

get_reservoir_states

get_reservoir_states() -> list[dict[str, Tensor]]

Return reservoir states for all sub-models.

RETURNS DESCRIPTION
list of dict

One dict per sub-model, mapping layer name to state tensor.

Source code in src/resdag/ensemble/coupled.py
396
397
398
399
400
401
402
403
404
def get_reservoir_states(self) -> list[dict[str, torch.Tensor]]:
    """Return reservoir states for all sub-models.

    Returns
    -------
    list of dict
        One dict per sub-model, mapping layer name to state tensor.
    """
    return [model.get_reservoir_states() for model in self._iter_models()]

get_state

get_state() -> ReservoirStates

Return initialized recurrent states in one named dictionary.

Source code in src/resdag/ensemble/coupled.py
406
407
408
409
410
411
412
def get_state(self) -> ReservoirStates:
    """Return initialized recurrent states in one named dictionary."""
    return {
        f"models.{index}.{name}": state
        for index, model in enumerate(self._iter_models())
        for name, state in model.get_state().items()
    }

set_state

set_state(states: Mapping[str, Tensor], strict: bool = True) -> None

Restore a named state dictionary matching forward_stateless.

Source code in src/resdag/ensemble/coupled.py
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
def set_state(self, states: Mapping[str, torch.Tensor], strict: bool = True) -> None:
    """Restore a named state dictionary matching `forward_stateless`."""
    names = {
        f"models.{index}.{name}"
        for index, model in enumerate(self._iter_models())
        for name, module in model.named_modules()
        if isinstance(module, BaseReservoirLayer)
    }
    if strict and set(states) != names:
        raise KeyError(
            f"Reservoir state keys must match the model; missing={sorted(names - set(states))}, "
            f"unexpected={sorted(set(states) - names)}"
        )
    for index, model in enumerate(self._iter_models()):
        prefix = f"models.{index}."
        member = {
            key.removeprefix(prefix): value
            for key, value in states.items()
            if key.startswith(prefix)
        }
        model.set_state(member, strict=strict)

set_reservoir_states

set_reservoir_states(states: list[dict[str, Tensor]], strict: bool = True) -> None

Restore reservoir states in all sub-models.

PARAMETER DESCRIPTION
states

One dict per sub-model as returned by get_reservoir_states.

TYPE: list of dict

strict

Forwarded to ESNModel.set_reservoir_states. When True (default), each sub-model raises on missing/unexpected reservoir keys.

TYPE: bool DEFAULT: True

RAISES DESCRIPTION
ValueError

If the number of dicts in states does not match self.n_models.

Source code in src/resdag/ensemble/coupled.py
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
def set_reservoir_states(
    self,
    states: list[dict[str, torch.Tensor]],
    strict: bool = True,
) -> None:
    """Restore reservoir states in all sub-models.

    Parameters
    ----------
    states : list of dict
        One dict per sub-model as returned by `get_reservoir_states`.
    strict : bool, default=True
        Forwarded to `ESNModel.set_reservoir_states`.  When
        `True` (default), each sub-model raises on missing/unexpected
        reservoir keys.

    Raises
    ------
    ValueError
        If the number of dicts in `states` does not match
        `self.n_models`.
    """
    if len(states) != self.n_models:
        raise ValueError(
            f"Expected {self.n_models} state dict(s) (one per sub-model), "
            f"got {len(states)}."
        )
    for model, state_dict in zip(self._iter_models(), states):
        model.set_reservoir_states(state_dict, strict=strict)

fit

fit(
    warmup_inputs: InputStreams,
    train_inputs: InputStreams,
    targets: ReadoutTargets,
    n_workers: int = 1,
    coerce: bool = False,
) -> None

Train all sub-models independently using resdag.training.ESNTrainer.

Each sub-model is trained separately on the same warmup/train data. Ensemble diversity comes from the different random reservoir initialisations of each sub-model.

Before dispatching to resdag.training.ESNTrainer, every warmup_inputs / train_inputs tensor and every targets value is checked against the ensemble's reference device/dtype (the first sub-model's first floating-point parameter; see _reference_device_dtype). A mismatch raises a clear, named ValueError — e.g. CPU targets fed to a GPU ensemble — instead of a raw cross-device RuntimeError deep inside the readout solve. Pass coerce=True to .to()-coerce the data to the reference instead of raising.

PARAMETER DESCRIPTION
warmup_inputs

Warmup sequences (feedback, driver1, ...). Shape of each: (batch, warmup_steps, features).

TYPE: tuple of torch.Tensor

train_inputs

Training sequences (feedback, driver1, ...). Shape of each: (batch, train_steps, features).

TYPE: tuple of torch.Tensor

targets

Mapping from readout name to target tensor. Shape of each target: (batch, train_steps, out_features).

TYPE: dict of str to torch.Tensor

n_workers

Number of worker threads used to fit sub-models concurrently. 1 (the default) runs sequentially in the calling thread. Larger values dispatch fits through a concurrent.futures.ThreadPoolExecutor — PyTorch releases the GIL during BLAS, so threading gives a real speed-up for CPU-bound CG ridge solves without the pickling cost of multiprocessing. On GPU, all workers share one device and may interfere via the same CUDA stream; benchmark before raising n_workers above 1 in that case.

TYPE: int DEFAULT: `1`

coerce

If False (default), a device/dtype mismatch between any input or target and the ensemble's sub-models raises a clear, named ValueError. If True, such tensors are coerced with .to(device=..., dtype=...) to the reference instead.

TYPE: bool DEFAULT: `False`

RAISES DESCRIPTION
ValueError

If n_workers < 1, or if coerce=False and any input/target tensor's device or dtype does not match the ensemble's sub-models.

Source code in src/resdag/ensemble/coupled.py
470
471
472
473
474
475
476
477
478
479
480
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
def fit(
    self,
    warmup_inputs: InputStreams,
    train_inputs: InputStreams,
    targets: ReadoutTargets,
    n_workers: int = 1,
    coerce: bool = False,
) -> None:
    """Train all sub-models independently using `resdag.training.ESNTrainer`.

    Each sub-model is trained separately on the same warmup/train data.
    Ensemble diversity comes from the different random reservoir
    initialisations of each sub-model.

    Before dispatching to `resdag.training.ESNTrainer`, every
    `warmup_inputs` / `train_inputs` tensor and every `targets` value
    is checked against the ensemble's reference device/dtype (the first
    sub-model's first floating-point parameter; see
    `_reference_device_dtype`).  A mismatch raises a clear, named
    `ValueError` — e.g. CPU targets fed to a GPU ensemble — instead
    of a raw cross-device `RuntimeError` deep inside the readout solve.
    Pass `coerce=True` to `.to()`-coerce the data to the reference
    instead of raising.

    Parameters
    ----------
    warmup_inputs : tuple of torch.Tensor
        Warmup sequences `(feedback, driver1, ...)`.
        Shape of each: `(batch, warmup_steps, features)`.
    train_inputs : tuple of torch.Tensor
        Training sequences `(feedback, driver1, ...)`.
        Shape of each: `(batch, train_steps, features)`.
    targets : dict of str to torch.Tensor
        Mapping from readout name to target tensor.
        Shape of each target: `(batch, train_steps, out_features)`.
    n_workers : int, default `1`
        Number of worker threads used to fit sub-models concurrently.
        `1` (the default) runs sequentially in the calling thread.
        Larger values dispatch fits through a
        `concurrent.futures.ThreadPoolExecutor` — PyTorch releases
        the GIL during BLAS, so threading gives a real speed-up for
        CPU-bound CG ridge solves without the pickling cost of
        multiprocessing.  On GPU, all workers share one device and may
        interfere via the same CUDA stream; benchmark before raising
        `n_workers` above 1 in that case.
    coerce : bool, default `False`
        If `False` (default), a device/dtype mismatch between any input or
        target and the ensemble's sub-models raises a clear, named
        `ValueError`.  If `True`, such tensors are coerced with
        `.to(device=..., dtype=...)` to the reference instead.

    Raises
    ------
    ValueError
        If `n_workers < 1`, or if `coerce=False` and any input/target
        tensor's device or dtype does not match the ensemble's sub-models.
    """
    if n_workers < 1:
        raise ValueError(f"n_workers must be >= 1, got {n_workers}.")

    warmup_inputs = ESNTrainer._input_tuple(warmup_inputs)
    train_inputs = ESNTrainer._input_tuple(train_inputs)
    if isinstance(targets, torch.Tensor):
        trainer = ESNTrainer(next(self._iter_models()))
        targets = trainer._target_dict(targets, trainer._discover_readouts())
    ref_device, ref_dtype = self._reference_device_dtype()
    warmup_inputs = tuple(
        self._coerce_tensor_to_reference(
            t, ref_device, ref_dtype, coerce=coerce, label=f"warmup_inputs[{i}]"
        )
        for i, t in enumerate(warmup_inputs)
    )
    train_inputs = tuple(
        self._coerce_tensor_to_reference(
            t, ref_device, ref_dtype, coerce=coerce, label=f"train_inputs[{i}]"
        )
        for i, t in enumerate(train_inputs)
    )
    targets = {
        name: self._coerce_tensor_to_reference(
            t, ref_device, ref_dtype, coerce=coerce, label=f"targets[{name!r}]"
        )
        for name, t in targets.items()
    }

    if n_workers == 1 or self.n_models == 1:
        for model in self._iter_models():
            ESNTrainer(model).fit(warmup_inputs, train_inputs, targets)
        return

    # Thread-pool path.  Each thread gets its own ESNTrainer over a
    # distinct sub-model, so there is no shared mutable state to guard.
    from concurrent.futures import ThreadPoolExecutor

    def _fit_one(model: ESNModel) -> None:
        ESNTrainer(model).fit(warmup_inputs, train_inputs, targets)

    with ThreadPoolExecutor(max_workers=min(n_workers, self.n_models)) as pool:
        list(pool.map(_fit_one, self.models))

forecast

forecast(
    warmup_inputs: tuple[Tensor, ...] | Tensor,
    forecast_inputs: tuple[Tensor, ...] | Tensor | None = None,
    *,
    horizon: int,
    initial_feedback: Tensor | None = None,
    return_warmup: bool = False,
    return_individuals: bool = False,
    reset: bool = True,
    alignment: ForecastAlignment = "next"
) -> Tensor | tuple[Tensor, list[Tensor]]

Forecast the immediate unseen samples using shared coupled feedback.

All members consume the same observed history. The aggregate of their final warmup predictions is slot zero, then each additional step consumes their previous aggregate. forecast_inputs contains future drivers starting immediately after history and needs horizon - 1 samples. A one-step forecast needs no future driver.

initial_feedback is a distinct extra input after all warmup inputs, shaped (batch, 1, feedback_features); when supplied, every prediction consumes a driver and an empty warmup is supported. reset=False continues saved states. alignment="legacy" reproduces the old convention which skipped the final warmup prediction and needs horizon future drivers. These semantics match ESNModel.forecast.

Results have shape (batch, horizon, output_features). With return_warmup=True, prepend historical predictions: total length is warmup_steps - 1 + horizon, or warmup_steps + horizon with an explicit seed or legacy alignment. With return_individuals=True, also return a list of member trajectories, each covering only the horizon future samples. Per-member buffers are allocated only when requested. horizon must be a positive integer; zero is rejected.

The final returned prediction has not been consumed. Continue with empty history, that prediction as initial_feedback, and reset=False.

Source code in src/resdag/ensemble/coupled.py
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
@torch.no_grad()
def forecast(
    self,
    warmup_inputs: tuple[torch.Tensor, ...] | torch.Tensor,
    forecast_inputs: tuple[torch.Tensor, ...] | torch.Tensor | None = None,
    *,
    horizon: int,
    initial_feedback: torch.Tensor | None = None,
    return_warmup: bool = False,
    return_individuals: bool = False,
    reset: bool = True,
    alignment: ForecastAlignment = "next",
) -> torch.Tensor | tuple[torch.Tensor, list[torch.Tensor]]:
    """Forecast the immediate unseen samples using shared coupled feedback.

    All members consume the same observed history. The aggregate of their
    final warmup predictions is slot zero, then each additional step consumes
    their previous aggregate. `forecast_inputs` contains future drivers
    starting immediately after history and needs `horizon - 1` samples.
    A one-step forecast needs no future driver.

    `initial_feedback` is a distinct extra input after all warmup inputs,
    shaped `(batch, 1, feedback_features)`; when supplied, every prediction
    consumes a driver and an empty warmup is supported. `reset=False`
    continues saved states. `alignment="legacy"` reproduces the old
    convention which skipped the final warmup prediction and needs
    `horizon` future drivers. These semantics match `ESNModel.forecast`.

    Results have shape `(batch, horizon, output_features)`. With
    `return_warmup=True`, prepend historical predictions: total length is
    `warmup_steps - 1 + horizon`, or `warmup_steps + horizon` with an
    explicit seed or legacy alignment. With `return_individuals=True`,
    also return a list of member trajectories, each covering only the
    `horizon` future samples. Per-member buffers are allocated only when
    requested. `horizon` must be a positive integer; zero is rejected.

    The final returned prediction has not been consumed. Continue with
    empty history, that prediction as `initial_feedback`, and `reset=False`.
    """
    models = list(self._iter_models())
    for model in models:
        model._get_execution_plan()
    warmup_inputs, drivers, horizon, boundary = prepare_forecast_inputs(
        warmup_inputs,
        forecast_inputs,
        num_inputs=len(models[0].inputs),
        horizon=horizon,
        initial_feedback=initial_feedback,
        alignment=alignment,
    )
    from resdag.core._hooks import has_execution_hooks

    if has_execution_hooks(self):
        return self._forecast_with_hooks(
            warmup_inputs,
            drivers,
            horizon=horizon,
            boundary=boundary,
            initial_feedback=initial_feedback,
            reset=reset,
            return_warmup=return_warmup,
            return_individuals=return_individuals,
        )
    batch_size = warmup_inputs[0].shape[0]
    device, dtype = self._reference_device_dtype()
    warmup_outputs_per_model = [
        cast(torch.Tensor, model.warmup(*warmup_inputs, return_outputs=True, reset=reset))
        for model in models
    ]
    output_size = warmup_outputs_per_model[0].shape[-1]
    forecast_outputs = torch.empty(batch_size, horizon, output_size, device=device, dtype=dtype)
    individual_outputs = (
        [torch.empty_like(forecast_outputs) for _ in models] if return_individuals else None
    )
    if initial_feedback is None:
        last_steps = [out[:, -1:, :] for out in warmup_outputs_per_model]
        current_feedback = self._coerce_step_for_buffer(
            self._aggregate(last_steps), device, dtype
        )
    else:
        last_steps = []
        current_feedback = self._coerce_step_for_buffer(initial_feedback, device, dtype)
    if boundary:
        forecast_outputs[:, :1, :] = current_feedback
        if individual_outputs is not None:
            for buf, out in zip(individual_outputs, last_steps):
                buf[:, :1, :] = self._coerce_step_for_buffer(out, device, dtype)

    flats: list[FlatStep] = [model._get_flat_step() for model in models]
    states_per_model = [
        self._resolve_member_states(flat, batch_size, device, dtype) for flat in flats
    ]
    for t in range(int(boundary), horizon):
        driver_idx = t - int(boundary)
        step_inputs = (current_feedback,) + tuple(
            driver[:, driver_idx : driver_idx + 1, :] for driver in drivers
        )
        step_outputs = []
        for i, flat in enumerate(flats):
            out_tuple, states_per_model[i] = flat.step(step_inputs, states_per_model[i])
            step_outputs.append(out_tuple[0])
        if individual_outputs is not None:
            for buf, out in zip(individual_outputs, step_outputs):
                buf[:, t : t + 1, :] = self._coerce_step_for_buffer(out, device, dtype)
        current_feedback = self._coerce_step_for_buffer(
            self._aggregate(step_outputs), device, dtype
        )
        forecast_outputs[:, t : t + 1, :] = current_feedback

    for flat, states in zip(flats, states_per_model):
        for reservoir, state in zip(flat.reservoir_layers, states):
            if reservoir.detach_state_between_calls and state.grad_fn is not None:
                reservoir.state = state.detach().clone()
            else:
                reservoir.state = state.clone()
    if return_warmup:
        warmup_avg = self._aggregate_stacked(torch.stack(warmup_outputs_per_model, dim=0))
        if warmup_avg.device != device:
            raise ValueError(
                f"Aggregated warmup output is on device={warmup_avg.device}, but "
                f"the forecast output buffer is on device={device}. A custom "
                "aggregator must keep its output on the sub-models' device."
            )
        warmup_avg = warmup_avg.to(dtype=dtype)
        prefix = warmup_avg[:, :-1, :] if boundary else warmup_avg
        forecast_outputs = torch.cat((prefix, forecast_outputs), dim=1)
    if individual_outputs is not None:
        return forecast_outputs, individual_outputs
    return forecast_outputs

save

save(path: str | Path, include_states: bool = False, **metadata: Any) -> None

Save ensemble weights (and optionally reservoir states) to a file.

PARAMETER DESCRIPTION
path

Destination file path.

TYPE: str

include_states

If True, also save current reservoir states for all sub-models.

TYPE: bool DEFAULT: `False`

**metadata

Arbitrary key-value pairs stored alongside the weights.

TYPE: Any DEFAULT: {}

Source code in src/resdag/ensemble/coupled.py
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
def save(
    self,
    path: str | Path,
    include_states: bool = False,
    **metadata: Any,
) -> None:
    """Save ensemble weights (and optionally reservoir states) to a file.

    Parameters
    ----------
    path : str
        Destination file path.
    include_states : bool, default `False`
        If `True`, also save current reservoir states for all sub-models.
    **metadata
        Arbitrary key-value pairs stored alongside the weights.
    """
    save_checkpoint(self, path, include_states, metadata)

load

load(
    path: str | Path,
    strict: bool = True,
    load_states: bool = False,
    map_location: Any = None,
) -> None

Load ensemble weights from a file created by save.

PARAMETER DESCRIPTION
path

Source file path.

TYPE: str

strict

Passed to load_state_dict for each sub-model.

TYPE: bool DEFAULT: `True`

load_states

If True, also restore reservoir states.

TYPE: bool DEFAULT: `False`

map_location

Passed to torch.load to remap saved storage devices.

TYPE: optional DEFAULT: None

RAISES DESCRIPTION
ValueError

If the checkpoint contains a different number of sub-models.

Source code in src/resdag/ensemble/coupled.py
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
def load(
    self,
    path: str | Path,
    strict: bool = True,
    load_states: bool = False,
    map_location: Any = None,
) -> None:
    """Load ensemble weights from a file created by `save`.

    Parameters
    ----------
    path : str
        Source file path.
    strict : bool, default `True`
        Passed to `load_state_dict` for each sub-model.
    load_states : bool, default `False`
        If `True`, also restore reservoir states.
    map_location : optional
        Passed to `torch.load` to remap saved storage devices.

    Raises
    ------
    ValueError
        If the checkpoint contains a different number of sub-models.
    """
    load_checkpoint(self, path, strict, load_states, map_location)

load_from_file classmethod

load_from_file(
    path: str | Path,
    model: CoupledEnsembleESNModel | None = None,
    strict: bool = True,
    load_states: bool = False,
    map_location: Any = None,
) -> CoupledEnsembleESNModel

Restore weights into an already constructed matching ensemble.

Source code in src/resdag/ensemble/coupled.py
849
850
851
852
853
854
855
856
857
858
859
860
861
862
@classmethod
def load_from_file(
    cls,
    path: str | Path,
    model: "CoupledEnsembleESNModel | None" = None,
    strict: bool = True,
    load_states: bool = False,
    map_location: Any = None,
) -> "CoupledEnsembleESNModel":
    """Restore weights into an already constructed matching ensemble."""
    if model is None:
        raise ValueError("model argument is required")
    model.load(path, strict=strict, load_states=load_states, map_location=map_location)
    return model

save_full

save_full(path: str | Path, **metadata: Any) -> None

Serialize the entire ensemble — every sub-model's architecture, weights, and reservoir states — to a single file.

Unlike save (state dicts only, requires rebuilding the ensemble before load), this pickles the whole ensemble object and is restored with load_full without rebuilding anything. Relies on the pickle support added in pytorch-symbolic 1.2.

PARAMETER DESCRIPTION
path

Destination file path.

TYPE: str

**metadata

Arbitrary key-value pairs stored alongside the ensemble.

TYPE: Any DEFAULT: {}

Notes

Loaded back with weights_only=False (arbitrary unpickling), so only open files you trust. Custom callable topology/initializer/activation specs must be importable (module-level, not lambdas) to be picklable; otherwise use the lighter state-dict save.

See Also

load_full : Reconstruct an ensemble saved with this method. save : Lighter, state-dict-only persistence (architecture not stored).

Source code in src/resdag/ensemble/coupled.py
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
def save_full(self, path: str | Path, **metadata: Any) -> None:
    """Serialize the entire ensemble — every sub-model's architecture,
    weights, and reservoir states — to a single file.

    Unlike `save` (state dicts only, requires rebuilding the ensemble
    before `load`), this pickles the whole ensemble object and is
    restored with `load_full` without rebuilding anything.  Relies on
    the pickle support added in `pytorch-symbolic` 1.2.

    Parameters
    ----------
    path : str
        Destination file path.
    **metadata
        Arbitrary key-value pairs stored alongside the ensemble.

    Notes
    -----
    Loaded back with `weights_only=False` (arbitrary unpickling), so only
    open files you trust.  Custom callable topology/initializer/activation
    specs must be importable (module-level, not lambdas) to be picklable;
    otherwise use the lighter state-dict `save`.

    See Also
    --------
    load_full : Reconstruct an ensemble saved with this method.
    save : Lighter, state-dict-only persistence (architecture not stored).
    """
    save_full_model(self, path, metadata)

load_full classmethod

load_full(
    path: str | Path,
    return_metadata: bool = False,
    map_location: Any = None,
    *,
    trusted: bool = False
) -> CoupledEnsembleESNModel | tuple[CoupledEnsembleESNModel, dict[str, Any]]

Reconstruct a complete ensemble saved with save_full.

No pre-built ensemble is required — every sub-model is restored intact.

PARAMETER DESCRIPTION
path

File path written by save_full.

TYPE: str

return_metadata

If True, return (ensemble, metadata) instead of just the ensemble.

TYPE: bool DEFAULT: `False`

map_location

Passed to torch.load to remap storage devices.

TYPE: optional DEFAULT: None

trusted

Explicit opt-in to execute the saved Python. Required for full pickle files; prefer Model.save and resdag.load otherwise.

TYPE: bool DEFAULT: False

RAISES DESCRIPTION
ValueError

If the file does not contain a whole ensemble (e.g. a state-dict checkpoint from save).

Warnings

Loads with weights_only=False, which unpickles arbitrary Python objects. Only call this on files from a source you trust.

See Also

save_full : Serialize a complete ensemble.

Source code in src/resdag/ensemble/coupled.py
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
@classmethod
def load_full(
    cls,
    path: str | Path,
    return_metadata: bool = False,
    map_location: Any = None,
    *,
    trusted: bool = False,
) -> "CoupledEnsembleESNModel | tuple[CoupledEnsembleESNModel, dict[str, Any]]":
    """Reconstruct a complete ensemble saved with `save_full`.

    No pre-built ensemble is required — every sub-model is restored intact.

    Parameters
    ----------
    path : str
        File path written by `save_full`.
    return_metadata : bool, default `False`
        If `True`, return `(ensemble, metadata)` instead of just the
        ensemble.
    map_location : optional
        Passed to `torch.load` to remap storage devices.

    trusted : bool, default=False
        Explicit opt-in to execute the saved Python. Required for full
        pickle files; prefer `Model.save` and `resdag.load` otherwise.

    Raises
    ------
    ValueError
        If the file does not contain a whole ensemble (e.g. a state-dict
        checkpoint from `save`).

    Warnings
    --------
    Loads with `weights_only=False`, which unpickles arbitrary Python
    objects.  Only call this on files from a source you trust.

    See Also
    --------
    save_full : Serialize a complete ensemble.
    """
    return load_full_model(cls, path, return_metadata, map_location, trusted=trusted)

aggregators

Ensemble Aggregators

This module hosts nn.Module layers that combine N per-sub-model outputs into a single aggregated tensor. Aggregators expect a 4-D input of shape (samples, batch, timesteps, features) (or a list of length samples each of shape (batch, timesteps, features)) and return a 3-D tensor of shape (batch, timesteps, features).

They plug into resdag.ensemble.CoupledEnsembleESNModel via the aggregator argument.

CLASS DESCRIPTION
OutliersFilteredMean

Mean across the samples dimension after dropping outliers (Z-score or IQR).

See Also

resdag.ensemble.CoupledEnsembleESNModel : Coupled ensemble that consumes these aggregators.

OutliersFilteredMean

OutliersFilteredMean(method: str = 'z_score', threshold: float | None = None)

Bases: Module

Mean over ensemble members after removing outlier norms.

For each (batch, timestep) location, computes the L2 norm of each member's feature vector, flags outliers via a robust modified Z-score or the IQR rule, then averages the inlier members. If every member is an outlier at a location, falls back to the plain mean.

The "z_score" method uses the modified Z-score 0.6745 * (x - median) / MAD (Iglewicz & Hoaglin, 1993), where MAD is the median absolute deviation. Unlike the classic mean/standard-deviation Z-score, the median and MAD are robust estimators: a single extreme member does not inflate the location/scale used to judge it, so a genuine outlier can be flagged even in small ensembles. (The classic non-robust Z-score saturates at sqrt(N - 1) for a lone outlier among N members, so a threshold=3.0 cutoff could never flag anything until N >= 11.)

PARAMETER DESCRIPTION
method

Outlier detection rule applied to per-member norms.

TYPE: (z_score, iqr) DEFAULT: "z_score"

threshold

Detection sensitivity. For "z_score" it is the modified-Z-score cutoff; for "iqr" it is the Tukey fence multiplier. When None, a method-appropriate default is used: 3.5 for "z_score" (the conventional modified-Z-score cutoff) and 1.5 for "iqr" (the conventional Tukey fence). Pass an explicit value to override.

TYPE: float or None DEFAULT: None

Examples:

>>> layer = OutliersFilteredMean(method="z_score")
>>> x = torch.randn(10, 3, 5, 4)  # samples, batch, time, features
>>> layer(x).shape
torch.Size([3, 5, 4])
RAISES DESCRIPTION
ValueError

If method is not "z_score" or "iqr".

References

Iglewicz, B. and Hoaglin, D. C. (1993). How to Detect and Handle Outliers. ASQC Quality Press.

PARAMETER DESCRIPTION
method

How to label outlier members along the samples axis.

TYPE: (z_score, iqr) DEFAULT: "z_score"

threshold

Detection sensitivity (modified-Z-score bound or IQR factor). When None, defaults to 3.5 for "z_score" and 1.5 for "iqr".

TYPE: float or None DEFAULT: None

RAISES DESCRIPTION
ValueError

If method is not supported.

Source code in src/resdag/ensemble/aggregators/outliers_filtered_mean.py
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
def __init__(self, method: str = "z_score", threshold: float | None = None) -> None:
    """Configure outlier detection.

    Parameters
    ----------
    method : {"z_score", "iqr"}, default="z_score"
        How to label outlier members along the samples axis.
    threshold : float or None, default=None
        Detection sensitivity (modified-Z-score bound or IQR factor). When
        `None`, defaults to `3.5` for `"z_score"` and `1.5` for
        `"iqr"`.

    Raises
    ------
    ValueError
        If *method* is not supported.
    """
    super().__init__()

    if method not in ["z_score", "iqr"]:
        raise ValueError(f"Unsupported method: {method}. Choose 'z_score' or 'iqr'.")

    self.method = method
    if threshold is None:
        threshold = _DEFAULT_Z_THRESHOLD if method == "z_score" else _DEFAULT_IQR_THRESHOLD
    self.threshold = threshold

forward

forward(input: Tensor | list[Tensor]) -> Tensor

Aggregate ensemble members with outlier filtering.

Outlier detection is norm-based and whole-member: each member's L2 feature-vector norm is scored at every (batch, timestep) location, and a flagged member is dropped in its entirety (the whole feature vector is excluded from that location's mean). A member that is an outlier in only one feature but normal in norm is therefore not caught, and one that is off in a single feature enough to inflate its norm is dropped wholesale rather than per feature.

PARAMETER DESCRIPTION
input

One of:

  • a 4-D tensor of shape (samples, batch, timesteps, features);
  • a 3-D tensor of shape (batch, timesteps, features), treated as a single-member ensemble (a samples axis of length one is inserted);
  • a list of length samples whose members are each 3-D (batch, timesteps, features) tensors.

TYPE: torch.Tensor or list of torch.Tensor

RETURNS DESCRIPTION
Tensor

Shape (batch, timesteps, features).

RAISES DESCRIPTION
ValueError

If input is a tensor whose rank is neither 3-D nor 4-D (for example a 2-D (samples, features) tensor, which would otherwise collapse silently to the wrong shape), or a list whose stacked members are not 4-D.

Source code in src/resdag/ensemble/aggregators/outliers_filtered_mean.py
 88
 89
 90
 91
 92
 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
def forward(self, input: torch.Tensor | list[torch.Tensor]) -> torch.Tensor:
    """Aggregate ensemble members with outlier filtering.

    Outlier detection is **norm-based and whole-member**: each member's L2
    feature-vector norm is scored at every `(batch, timestep)` location,
    and a flagged member is dropped in its entirety (the whole feature
    vector is excluded from that location's mean). A member that is an
    outlier in only one feature but normal in norm is therefore *not*
    caught, and one that is off in a single feature enough to inflate its
    norm is dropped wholesale rather than per feature.

    Parameters
    ----------
    input : torch.Tensor or list of torch.Tensor
        One of:

        - a 4-D tensor of shape `(samples, batch, timesteps, features)`;
        - a 3-D tensor of shape `(batch, timesteps, features)`, treated
          as a single-member ensemble (a `samples` axis of length one is
          inserted);
        - a list of length *samples* whose members are each 3-D
          `(batch, timesteps, features)` tensors.

    Returns
    -------
    torch.Tensor
        Shape `(batch, timesteps, features)`.

    Raises
    ------
    ValueError
        If *input* is a tensor whose rank is neither 3-D nor 4-D (for
        example a 2-D `(samples, features)` tensor, which would otherwise
        collapse silently to the wrong shape), or a list whose stacked
        members are not 4-D.
    """
    if isinstance(input, list):
        input = torch.stack(input, dim=0)
        if input.dim() != 4:
            raise ValueError(
                "OutliersFilteredMean expects a list of 3D "
                "(batch, timesteps, features) tensors, but stacking the "
                f"members produced a {input.dim()}D tensor with shape "
                f"{tuple(input.shape)}"
            )
    elif input.dim() == 3:
        input = input.unsqueeze(0)
    elif input.dim() != 4:
        raise ValueError(
            "OutliersFilteredMean expects a 4D "
            "(samples, batch, timesteps, features) tensor, a 3D "
            "(batch, timesteps, features) tensor, or a list of 3D tensors, "
            f"but got a {input.dim()}D tensor with shape {tuple(input.shape)}"
        )

    norms = torch.norm(input, p=2, dim=-1)
    finite = torch.isfinite(input).all(dim=-1) & torch.isfinite(norms)
    invalid_positions = ~finite.any(dim=0)
    if invalid_positions.any():
        positions = invalid_positions.nonzero().detach().cpu().tolist()
        raise ValueError(
            f"All {input.shape[0]} ensemble members have non-finite predictions or "
            f"prediction norms at (batch, timestep) positions {positions[:5]}. "
            "Check the member forecasts before continuing coupled feedback."
        )

    if self.method == "z_score":
        mask = self._mask_modified_z_score(norms, finite)
    else:
        mask = self._mask_iqr(norms, finite)

    # Multiplication cannot remove NaN/Inf (Inf * 0 is NaN). Exclude
    # invalid members before any arithmetic, including the fallback mean.
    work = input.float() if input.dtype in (torch.float16, torch.bfloat16) else input
    safe_input = torch.where(finite.unsqueeze(-1), work, 0)
    plain_mean = safe_input.sum(dim=0) / finite.sum(dim=0).unsqueeze(-1)
    mask_expanded = (mask & finite).unsqueeze(-1)
    masked_input = torch.where(mask_expanded, work, 0)
    sum_inliers = masked_input.sum(dim=0)
    count_inliers = mask_expanded.sum(dim=0).expand_as(sum_inliers)

    mean_result = torch.where(
        count_inliers > 0,
        sum_inliers / count_inliers.clamp(min=1),
        plain_mean,
    )

    return mean_result.to(dtype=input.dtype)