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 |
| CLASS | DESCRIPTION |
|---|---|
KnowledgeModel |
|
ParallelESNModel |
The model class |
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:
|
feedback_size
|
Number of feedback features (input dimension).
TYPE:
|
output_size
|
Number of output features.
TYPE:
|
input_size
|
Dimension of an optional driving (exogenous) input. When given, the
model takes two inputs
TYPE:
|
input_initializer
|
Initializer for the driving-input weights. Same accepted forms as
TYPE:
|
topology
|
Topology for recurrent weights. Accepts:
TYPE:
|
spectral_radius
|
Desired spectral radius for recurrent weights.
TYPE:
|
leak_rate
|
Leaky integration rate (1.0 = no leak).
TYPE:
|
noise
|
Standard deviation of additive Gaussian state noise injected into the
reservoir after the activation. Active only in training mode (a no-op
under
TYPE:
|
feedback_initializer
|
Initializer for feedback weights. Accepts:
TYPE:
|
activation
|
Activation function (
TYPE:
|
bias
|
Whether to use bias in the reservoir.
TYPE:
|
trainable
|
Whether reservoir weights are trainable.
TYPE:
|
readout
|
A built-in name (
TYPE:
|
readout_alpha
|
Ridge regression regularization for readout.
TYPE:
|
readout_bias
|
Whether to use bias in the readout.
TYPE:
|
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:
|
readout_name
|
Name for the readout layer (used in training targets).
TYPE:
|
readout_kwargs
|
Extra readout options, such as
TYPE:
|
**reservoir_kwargs
|
Additional keyword arguments passed to
TYPE:
|
| 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 | |
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:
|
model_factory
|
Factory that creates one
TYPE:
|
aggregate
|
Aggregation strategy applied to the N model outputs at each autoregressive step:
|
seed
|
Master seed for deterministic sub-model construction. Sub-model
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:
|
**model_kwargs
|
All remaining keyword arguments are forwarded verbatim to each
TYPE:
|
| 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 | |
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
TYPE:
|
n_layers
|
Number of stacked layers. Required when
TYPE:
|
feedback_size
|
Number of feedback features driving the first layer (the input dimension of the model).
TYPE:
|
output_size
|
Number of output features. For autoregressive
TYPE:
|
concat_all_states
|
When
TYPE:
|
interlayer_scaling
|
Magnitude of the inter-layer coupling weights (layers
TYPE:
|
topology
|
Topology for the recurrent weights, shared by every layer. Accepts a
registry name, a
TYPE:
|
spectral_radius
|
Target spectral radius for the recurrent weights of every layer.
TYPE:
|
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.
TYPE:
|
feedback_initializer
|
Initializer for the feedback weights, shared by every layer. Same
accepted forms as
TYPE:
|
activation
|
Activation function for every layer (
TYPE:
|
bias
|
Whether every reservoir layer uses a bias term.
TYPE:
|
trainable
|
Whether the reservoir weights are trainable.
TYPE:
|
readout
|
A built-in name (
TYPE:
|
readout_alpha
|
Ridge regression regularization for the readout.
TYPE:
|
readout_bias
|
Whether the readout uses a bias term.
TYPE:
|
readout_name
|
Name for the readout layer (used as the target key in training).
TYPE:
|
readout_kwargs
|
Extra readout options, such as
TYPE:
|
**reservoir_kwargs
|
Additional keyword arguments forwarded to every
TYPE:
|
| 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,
|
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 | |
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:
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:
|
feedback_size
|
Number of feedback features (autoregressive input dimension).
TYPE:
|
output_size
|
Number of output features.
TYPE:
|
beta
|
Proximity to the edge of stability in \((0, 1]\). Smaller values
weight the orthogonal skip (longer memory);
TYPE:
|
input_size
|
Dimension of an optional driving (exogenous) input. When given, the
model takes two inputs
TYPE:
|
input_initializer
|
Initializer for the driving-input weights. Only used when
TYPE:
|
topology
|
Topology for the recurrent weights
TYPE:
|
spectral_radius
|
Target spectral radius for the recurrent weights
TYPE:
|
orthogonal_scaling
|
Gain on the orthogonal skip matrix
TYPE:
|
feedback_initializer
|
Initializer for the feedback weights.
TYPE:
|
activation
|
Activation for the nonlinear branch.
TYPE:
|
bias
|
Whether to use a bias in the reservoir.
TYPE:
|
trainable
|
Whether the reservoir weights are trainable. The orthogonal skip stays frozen regardless.
TYPE:
|
readout
|
A built-in name (
TYPE:
|
readout_alpha
|
Ridge regularization for the readout.
TYPE:
|
readout_bias
|
Whether to use a bias in the readout.
TYPE:
|
readout_name
|
Name for the readout layer (used as the target key in training).
TYPE:
|
readout_kwargs
|
Extra readout options, such as
TYPE:
|
**reservoir_kwargs
|
Additional keyword arguments forwarded to
TYPE:
|
| 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 | |
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:
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:
|
feedback_size
|
Number of feedback features (autoregressive input dimension).
TYPE:
|
output_size
|
Number of output features.
TYPE:
|
epsilon
|
Forward-Euler step size \(\varepsilon\). Smaller values sit the reservoir closer to the edge of stability (longer, near-lossless memory).
TYPE:
|
gamma
|
Diffusion coefficient \(\gamma \ge 0\) damping the Euler
discretization error.
TYPE:
|
input_size
|
Dimension of an optional driving (exogenous) input. When given, the
model takes two inputs
TYPE:
|
input_initializer
|
Initializer for the driving-input weights. Only used when
TYPE:
|
topology
|
Topology for the recurrent weights
TYPE:
|
spectral_radius
|
Target rotation rate for
TYPE:
|
substeps
|
Fixed integration sub-steps per interval.
TYPE:
|
solver
|
Integration scheme.
TYPE:
|
feedback_initializer
|
Initializer for the feedback weights.
TYPE:
|
activation
|
Activation of the vector field (
TYPE:
|
bias
|
Whether to use a bias in the reservoir.
TYPE:
|
trainable
|
Whether the reservoir weights are trainable.
TYPE:
|
readout
|
A built-in name (
TYPE:
|
readout_alpha
|
Ridge regularization for the readout.
TYPE:
|
readout_bias
|
Whether to use a bias in the readout.
TYPE:
|
readout_name
|
Name for the readout layer (used as the target key in training).
TYPE:
|
readout_kwargs
|
Extra readout options, such as
TYPE:
|
**reservoir_kwargs
|
Additional keyword arguments forwarded to
TYPE:
|
| 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 | |
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:
|
feedback_size
|
Number of feedback features (input dimension).
TYPE:
|
output_size
|
Number of output features.
TYPE:
|
input_size
|
Dimension of an optional driving (exogenous) input. When given, the
model takes two inputs
TYPE:
|
input_initializer
|
Initializer for the driving-input weights. Only used when
TYPE:
|
topology
|
Topology for the recurrent candidate weight. The update-gate recurrent weight is always dense-random.
TYPE:
|
spectral_radius
|
Desired spectral radius for the recurrent candidate weight.
TYPE:
|
update_gate_bias
|
Retention bias on the update gate (keeps a frozen gated reservoir from
washing out its memory). See
TYPE:
|
activation
|
Candidate nonlinearity (LiGRU default is
TYPE:
|
gate_activation
|
Update-gate nonlinearity.
TYPE:
|
feedback_initializer
|
Initializer for feedback weights.
TYPE:
|
bias
|
Whether to use gate biases in the reservoir.
TYPE:
|
trainable
|
Whether reservoir weights are trainable. A frozen gated reservoir often
underperforms an ESN;
TYPE:
|
concat_input
|
Whether to concatenate the raw input with the reservoir output before the readout.
TYPE:
|
readout
|
A built-in name (
TYPE:
|
readout_alpha
|
Ridge regularization for the readout.
TYPE:
|
readout_bias
|
Whether to use bias in the readout.
TYPE:
|
readout_name
|
Name for the readout layer (used as the target key in training).
TYPE:
|
readout_kwargs
|
Extra readout options, such as
TYPE:
|
**reservoir_kwargs
|
Additional keyword arguments forwarded to
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
`resdag.core.ESNModel`
|
Configured gated ESN model ready for training and inference. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
TypeError
|
If |
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 | |
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:
|
feedback_size
|
Number of feedback features.
TYPE:
|
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:
|
spectral_radius
|
Desired spectral radius for recurrent weights.
TYPE:
|
leak_rate
|
Leaky integration rate (1.0 = no leak).
TYPE:
|
feedback_initializer
|
Initializer for feedback weights.
TYPE:
|
activation
|
Activation function ("tanh", "relu", "sigmoid", "identity").
TYPE:
|
bias
|
Whether to use bias in the reservoir.
TYPE:
|
trainable
|
Whether reservoir weights are trainable.
TYPE:
|
**reservoir_kwargs
|
Additional keyword arguments passed to ESNLayer.
TYPE:
|
| 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 | |
KnowledgeModel
¶
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 |
model_out_size
|
Feature dimension of
TYPE:
|
| ATTRIBUTE | DESCRIPTION |
|---|---|
fn |
The wrapped knowledge model. Registered as a submodule when it is an
|
model_out_size |
The declared output feature dimension.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
At |
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 |
ValueError
|
If |
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 | |
forward
¶
Apply the knowledge model to the current state u.
| PARAMETER | DESCRIPTION |
|---|---|
u
|
Current state of shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The one-step-ahead prediction of shape
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the wrapped model's output rank differs from |
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 | |
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 /
TYPE:
|
reservoir_size
|
Number of units in the reservoir.
TYPE:
|
feedback_size
|
Number of feedback features (the input dimension of the model,
TYPE:
|
output_size
|
Number of output features. For autoregressive
TYPE:
|
model_out_size
|
Feature dimension of the knowledge model's output. Only used when
TYPE:
|
gamma
|
Fraction of reservoir units wired to the raw-state block
TYPE:
|
input_scaling
|
Half-width of the informed input weights: each nonzero entry is drawn
uniformly from
TYPE:
|
topology
|
Topology for the recurrent weights. Accepts a registry name, a
TYPE:
|
spectral_radius
|
Target spectral radius for the recurrent weights.
TYPE:
|
leak_rate
|
Leaky-integration rate (1.0 = no leak).
TYPE:
|
activation
|
Activation function (
TYPE:
|
bias
|
Whether the reservoir uses a bias term.
TYPE:
|
trainable
|
Whether the reservoir weights are trainable.
TYPE:
|
readout
|
A built-in name (
TYPE:
|
readout_alpha
|
Ridge regression regularization for the readout.
TYPE:
|
readout_bias
|
Whether the readout uses a bias term.
TYPE:
|
readout_name
|
Name for the readout layer (used as the target key in training).
TYPE:
|
readout_kwargs
|
Extra readout options, such as
TYPE:
|
**reservoir_kwargs
|
Additional keyword arguments forwarded to
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
`resdag.core.ESNModel`
|
The assembled hybrid ESN, ready for training and forecasting. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
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 | |
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:
|
feedback_size
|
Number of feedback features.
TYPE:
|
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:
|
spectral_radius
|
Desired spectral radius for recurrent weights.
TYPE:
|
leak_rate
|
Leaky integration rate (1.0 = no leak).
TYPE:
|
feedback_initializer
|
Initializer for feedback weights.
TYPE:
|
bias
|
Whether to use bias in the reservoir.
TYPE:
|
trainable
|
Whether reservoir weights are trainable.
TYPE:
|
**reservoir_kwargs
|
Additional keyword arguments passed to ESNLayer.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ESNModel
|
ESN model with linear reservoir activation. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
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 | |
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:
|
feedback_size
|
Number of input features driving the reservoir.
TYPE:
|
output_size
|
Number of output (target) features.
TYPE:
|
input_size
|
Dimension of an optional second driving input. When given, the model
takes two inputs
TYPE:
|
input_initializer
|
Initializer for the driving-input weights. Only used when
TYPE:
|
tau_mem
|
Membrane time constant \(\tau_\text{mem}\) (in units of
TYPE:
|
tau_syn
|
Synaptic time constant \(\tau_\text{syn}\). Only used when
TYPE:
|
dt
|
Integration timestep \(\Delta t\).
TYPE:
|
synaptic_current
|
If
TYPE:
|
v_threshold
|
Firing threshold.
TYPE:
|
reset
|
Membrane reset on a spike (soft subtract vs hard zero).
TYPE:
|
surrogate_beta
|
Fast-sigmoid surrogate slope for the straight-through spike gradient
(only matters when
TYPE:
|
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:
|
topology
|
Topology for the recurrent spike-coupling weight
TYPE:
|
spectral_radius
|
Target spectral radius for
TYPE:
|
feedback_initializer
|
Initializer for the feedback weights.
TYPE:
|
bias
|
Whether to use a bias current in the reservoir.
TYPE:
|
trainable
|
Whether the reservoir weights are trainable (via the surrogate spike
gradient). A frozen liquid + fitted readout is the classic LSM; set
TYPE:
|
concat_input
|
Whether to concatenate the raw input with the reservoir trace before the readout.
TYPE:
|
readout
|
A built-in name (
TYPE:
|
readout_alpha
|
Ridge regularization for the readout.
TYPE:
|
readout_bias
|
Whether to use a bias in the readout.
TYPE:
|
readout_name
|
Name for the readout layer (the target key in training).
TYPE:
|
readout_kwargs
|
Extra readout options, such as
TYPE:
|
**reservoir_kwargs
|
Additional keyword arguments forwarded to
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
`resdag.core.ESNModel`
|
Configured LSM model ready for driven training and inference. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
TypeError
|
If |
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 | |
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:
|
feedback_size
|
Dimension of feedback signal (input features).
TYPE:
|
output_size
|
Dimension of output signal.
TYPE:
|
input_size
|
Dimension of an optional driving (exogenous) input. When given, the
model takes two inputs
TYPE:
|
input_initializer
|
Initializer for the driving-input weights. Same format as
TYPE:
|
topology
|
Topology for recurrent weights. Accepts:
TYPE:
|
spectral_radius
|
Target spectral radius for recurrent weights.
TYPE:
|
leak_rate
|
Leaky integration rate. 1.0 = no leaking (standard ESN).
TYPE:
|
feedback_initializer
|
Initializer for feedback weights. Same format as
TYPE:
|
activation
|
Activation function for reservoir neurons.
TYPE:
|
bias
|
Whether to include bias in reservoir.
TYPE:
|
trainable
|
If True, reservoir weights are trainable via backpropagation.
TYPE:
|
readout
|
A built-in name (
TYPE:
|
readout_alpha
|
L2 regularization strength for ridge regression in readout.
TYPE:
|
readout_bias
|
Whether to include bias in readout layer.
TYPE:
|
readout_name
|
Name for the readout layer. Used as target key in training.
TYPE:
|
readout_kwargs
|
Extra readout constructor options, including
TYPE:
|
**reservoir_kwargs
|
Additional keyword arguments passed to
TYPE:
|
| 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 | |
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
TYPE:
|
readout
|
The weight-tied readout. Its
TYPE:
|
input_dim
|
Full spatial dimension
TYPE:
|
core_width
|
Core width
TYPE:
|
halo
|
Halo width
TYPE:
|
| ATTRIBUTE | DESCRIPTION |
|---|---|
reservoir |
The shared reservoir layer.
TYPE:
|
readout |
The weight-tied readout layer.
TYPE:
|
n_patches |
Number of patches
TYPE:
|
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 | |
forward
¶
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 | |
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 | |
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 | |
window
¶
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
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Windowed input of shape |
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 | |
stitch
¶
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
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Full field of shape |
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 | |
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 | |
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 | |
set_state
¶
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 | |
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 | |
set_reservoir_states
¶
Restore named recurrent state; alias of set_state.
Source code in src/resdag/models/parallel_esn.py
400 401 402 | |
fit
¶
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
TYPE:
|
train
|
Training field of shape
TYPE:
|
targets
|
Next-step field of shape
TYPE:
|
reset
|
If
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If any input is not 3-D, if their feature dimension is not
|
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 | |
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 | |
save
¶
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 | |
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 | |
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 | |
save_full
¶
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. |
**metadata
|
Additional metadata stored alongside the model.
TYPE:
|
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 | |
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 |
return_metadata
|
If
TYPE:
|
map_location
|
Passed to
TYPE:
|
trusted
|
Explicit opt-in to execute the saved Python. Required for full
pickle files; prefer
TYPE:
|
| 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 | |
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
TYPE:
|
core_width
|
Core width
TYPE:
|
halo
|
Halo width
TYPE:
|
reservoir_size
|
Number of units
TYPE:
|
topology
|
Topology for the recurrent weights. Accepts a registry name, a
TYPE:
|
spectral_radius
|
Target spectral radius for the recurrent weights.
TYPE:
|
leak_rate
|
Leaky-integration rate (1.0 = no leak).
TYPE:
|
input_scaling
|
Scale of the per-patch input (feedback) weights when
TYPE:
|
feedback_initializer
|
Initializer for the per-patch input weights. Same accepted forms as
TYPE:
|
activation
|
Activation function (
TYPE:
|
bias
|
Whether the reservoir uses a bias term.
TYPE:
|
trainable
|
Whether the reservoir weights are trainable.
TYPE:
|
seed
|
Reproducibility seed fixing every reservoir parameter. |
readout
|
A built-in readout name or a ReadoutLayer subclass, with the same
solver choices as
TYPE:
|
readout_alpha
|
Ridge regularization for the readout.
TYPE:
|
readout_bias
|
Whether the readout uses a bias term.
TYPE:
|
readout_name
|
Name for the readout layer.
TYPE:
|
readout_kwargs
|
Additional readout constructor options. Architecture widths are fixed.
TYPE:
|
**reservoir_kwargs
|
Additional keyword arguments forwarded to
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ParallelESNModel
|
The assembled parallel reservoir, ready for |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
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 | |
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:
|
feedback_size
|
Dimension of feedback signal (input features).
TYPE:
|
output_size
|
Dimension of output signal.
TYPE:
|
exponent
|
Exponent applied to every reservoir state. Tanh reservoir states
live in
TYPE:
|
input_size
|
Dimension of an optional driving (exogenous) input. When given, the
model takes two inputs
TYPE:
|
input_initializer
|
Initializer for the driving-input weights. Same format as
TYPE:
|
topology
|
Topology for recurrent weights. Accepts:
TYPE:
|
spectral_radius
|
Target spectral radius for recurrent weights.
TYPE:
|
leak_rate
|
Leaky integration rate. 1.0 = no leaking (standard ESN).
TYPE:
|
feedback_initializer
|
Initializer for feedback weights. Same format as
TYPE:
|
activation
|
Activation function for reservoir neurons.
TYPE:
|
bias
|
Whether to include bias in reservoir.
TYPE:
|
trainable
|
If True, reservoir weights are trainable via backpropagation.
TYPE:
|
readout
|
A built-in name (
TYPE:
|
readout_alpha
|
L2 regularization strength for ridge regression in readout.
TYPE:
|
readout_bias
|
Whether to include bias in readout layer.
TYPE:
|
readout_name
|
Name for the readout layer. Used as target key in training.
TYPE:
|
readout_kwargs
|
Extra readout constructor options, including
TYPE:
|
**reservoir_kwargs
|
Additional keyword arguments passed to
TYPE:
|
| 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 nonan/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 producenanunder the defaulttorch.pow, silently corrupting the readout inputs. Negative exponents (e.g.-1.0) produceinfon the zeros thattanhstates 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 | |
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:
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:
|
feedback_size
|
Number of feedback features (autoregressive input dimension).
TYPE:
|
output_size
|
Number of output features.
TYPE:
|
alpha
|
Scaling of the orthogonal skip (residual) branch.
TYPE:
|
beta
|
Scaling of the nonlinear branch.
TYPE:
|
input_size
|
Dimension of an optional driving (exogenous) input. When given, the
model takes two inputs
TYPE:
|
input_initializer
|
Initializer for the driving-input weights. Only used when
TYPE:
|
topology
|
Topology for the recurrent weights
TYPE:
|
spectral_radius
|
Target spectral radius for the recurrent weights
TYPE:
|
orthogonal_scaling
|
Gain on the orthogonal skip matrix
TYPE:
|
feedback_initializer
|
Initializer for the feedback weights.
TYPE:
|
activation
|
Activation for the nonlinear branch.
TYPE:
|
bias
|
Whether to use a bias in the reservoir.
TYPE:
|
trainable
|
Whether the reservoir weights are trainable. The orthogonal skip stays frozen regardless.
TYPE:
|
readout
|
A built-in name (
TYPE:
|
readout_alpha
|
Ridge regularization for the readout.
TYPE:
|
readout_bias
|
Whether to use a bias in the readout.
TYPE:
|
readout_name
|
Name for the readout layer (used as the target key in training).
TYPE:
|
readout_kwargs
|
Extra readout options, such as
TYPE:
|
**reservoir_kwargs
|
Additional keyword arguments forwarded to
TYPE:
|
| 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 | |
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
¶
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:
|
aggregator
|
How to combine the N per-model outputs into a single feedback tensor.
|
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:
|
aggregator
|
Aggregation strategy. See class docstring for options. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
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 | |
forward
¶
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:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Aggregated output of shape |
Source code in src/resdag/ensemble/coupled.py
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 | |
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 | |
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 | |
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:
|
Source code in src/resdag/ensemble/coupled.py
375 376 377 378 379 380 381 382 383 384 385 | |
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 | |
get_reservoir_states
¶
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 | |
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 | |
set_state
¶
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 | |
set_reservoir_states
¶
Restore reservoir states in all sub-models.
| PARAMETER | DESCRIPTION |
|---|---|
states
|
One dict per sub-model as returned by
TYPE:
|
strict
|
Forwarded to
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the number of dicts in |
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 | |
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
TYPE:
|
train_inputs
|
Training sequences
TYPE:
|
targets
|
Mapping from readout name to target tensor.
Shape of each target:
TYPE:
|
n_workers
|
Number of worker threads used to fit sub-models concurrently.
TYPE:
|
coerce
|
If
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
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 | |
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 | |
save
¶
Save ensemble weights (and optionally reservoir states) to a file.
| PARAMETER | DESCRIPTION |
|---|---|
path
|
Destination file path.
TYPE:
|
include_states
|
If
TYPE:
|
**metadata
|
Arbitrary key-value pairs stored alongside the weights.
TYPE:
|
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 | |
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:
|
strict
|
Passed to
TYPE:
|
load_states
|
If
TYPE:
|
map_location
|
Passed to
TYPE:
|
| 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 | |
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 | |
save_full
¶
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:
|
**metadata
|
Arbitrary key-value pairs stored alongside the ensemble.
TYPE:
|
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 | |
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
TYPE:
|
return_metadata
|
If
TYPE:
|
map_location
|
Passed to
TYPE:
|
trusted
|
Explicit opt-in to execute the saved Python. Required for full
pickle files; prefer
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the file does not contain a whole ensemble (e.g. a state-dict
checkpoint from |
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 | |
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
¶
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:
|
threshold
|
Detection sensitivity. For
TYPE:
|
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 |
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:
|
threshold
|
Detection sensitivity (modified-Z-score bound or IQR factor). When
TYPE:
|
| 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 | |
forward
¶
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:
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Shape |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If input is a tensor whose rank is neither 3-D nor 4-D (for
example a 2-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 | |