Reference
Layers¶
The nn.Module components used to build models: single-step reservoir
cells, the stateful sequence layers that wrap them, readout layers, and
transform layers. All are importable directly from resdag.layers.
For automatic fitting, solver overrides and diagnostics, start with the
readout solver guide. rd.ESN uses
AutoReadoutLayer by default; lower-level factories expose it as readout="auto".
Single-step cells¶
The public extension contract is ReservoirCell: implement state_size,
output_size, init_state and forward(inputs, state). Override
validate_state for a different packed-state layout. Optional project_inputs
and step split a sequence projection from the recurrent update; override
both together. These are supported subclass hooks, not implementation helpers.
Continuous cells add vector_field and optional output_from_state; spiking
cells add neuron_update. Their documented state packing is part of each
contract. See custom components for a
complete cell, transform and readout example.
cells
¶
ReservoirCell
¶
Abstract base for a single-timestep reservoir state update.
Owns all trainable (or frozen) parameters. Sequence iteration is
handled by the enclosing BaseReservoirLayer, not by the cell
itself.
Notes
Subclasses must implement state_size, output_size,
init_state, and forward.
inputs[0] passed to forward is always the feedback slice.
Additional elements are driving inputs in the order they were passed to
the layer's forward.
For cells where the output and the state are the same tensor (e.g.
ESNCell), output_size == state_size. For cells where they
differ (e.g. NGCell whose output is a feature vector but whose
state is a delay buffer), the two properties return different values.
See Also
resdag.layers.ESNCell : Concrete ESN cell implementation. resdag.layers.cells.ngrc_cell.NGCell : NG-RC cell implementation. resdag.layers.BaseReservoirLayer : Layer that drives the cell.
output_size
abstractmethod
property
¶
output_size: int
Dimensionality of the per-step output vector.
init_state
abstractmethod
¶
Return a zero initial state tensor.
| PARAMETER | DESCRIPTION |
|---|---|
batch_size
|
Number of samples in the batch.
TYPE:
|
device
|
Target device.
TYPE:
|
dtype
|
Target dtype.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Zero-filled initial state. |
Source code in src/resdag/layers/cells/base_cell.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 | |
forward
abstractmethod
¶
Compute the per-step output and next state from current inputs and state.
| PARAMETER | DESCRIPTION |
|---|---|
inputs
|
Per-timestep input slices, one per input stream, each of shape
|
state
|
Current state tensor.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
output
|
Per-step output of shape
TYPE:
|
new_state
|
Updated state tensor.
TYPE:
|
Source code in src/resdag/layers/cells/base_cell.py
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 | |
project_inputs
¶
Optional sequence-level fast path: precompute input contributions.
Cells whose pre-activation splits into an input-dependent part and a state-dependent part (e.g. the leaky ESN) can compute the input-dependent part for the whole sequence in one batched matmul, leaving only the recurrent term inside the time loop. This cuts the per-step kernel count roughly in half — the difference between the GPU being slower and faster than the CPU for typical reservoir sizes.
| PARAMETER | DESCRIPTION |
|---|---|
inputs
|
Full input sequences, one per stream, each of shape
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor or None
|
Precomputed projection of shape |
Source code in src/resdag/layers/cells/base_cell.py
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 | |
step
¶
Single-step update consuming a slice of project_inputs.
Only called by the layer when project_inputs returned a
tensor. Subclasses implementing the fast path must override both
methods together.
| PARAMETER | DESCRIPTION |
|---|---|
projected_t
|
Per-timestep slice of the precomputed projection, shape
TYPE:
|
state
|
Current state tensor.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
output
|
Per-step output.
TYPE:
|
new_state
|
Updated state tensor.
TYPE:
|
Source code in src/resdag/layers/cells/base_cell.py
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 | |
validate_state
¶
validate_state(state: Tensor) -> None
Validate that state matches the layout this cell expects.
The base implementation enforces the 2-D (batch, state_size)
contract used by classical RNN-style cells (e.g. ESNCell).
Cells with a different state layout — for example
resdag.layers.cells.ngrc_cell.NGCell whose state is a 3-D
delay buffer — override this method to check their own shape.
| PARAMETER | DESCRIPTION |
|---|---|
state
|
Candidate state tensor to validate.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Source code in src/resdag/layers/cells/base_cell.py
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 | |
ESNCell
¶
ESNCell(
reservoir_size: int,
feedback_size: int,
input_size: int | None = None,
spectral_radius: float | None = None,
bias: bool = True,
bias_scaling: float = 1.0,
activation: str = "tanh",
leak_rate: float | Tensor | Sequence[float] = 1.0,
noise: float = 0.0,
trainable: bool = False,
sparse: SparseSpec = False,
feedback_initializer: InitializerSpec = None,
input_initializer: InitializerSpec = None,
topology: TopologySpec = None,
seed: SeedLike = None,
*,
recurrent_initializer: TopologySpec = None,
bias_initializer: InitializerSpec = None,
initial_state_initializer: InitializerSpec = None,
device: device | str | None = None,
dtype: dtype | None = None
)
Bases: CompactRecurrentMixin, ReservoirCell
Single-timestep leaky Echo State Network update.
Owns all weight matrices and bias. Sequence iteration is delegated to
the enclosing ESNLayer.
The state update follows the standard leaky-integrator ESN equation (Jaeger 2001; Lukoševičius 2012):
where \(f\) is the activation function, \(\alpha\) is the leak
rate, \(W_{fb}\) is the feedback weight matrix, \(W_{in}\) is the
(optional) input weight matrix, \(W_{rec}\) is the recurrent
weight matrix, and \(b\) is a fixed random bias drawn from
\(\mathcal{U}(-\beta, \beta)\) with \(\beta\) = bias_scaling.
The bias breaks the odd symmetry of tanh dynamics: without it,
negated inputs produce exactly negated states, which constrains the
representations the readout can draw from.
| PARAMETER | DESCRIPTION |
|---|---|
reservoir_size
|
Number of reservoir units (hidden state dimension).
TYPE:
|
feedback_size
|
Dimension of feedback signal. Required for all ESN cells.
TYPE:
|
input_size
|
Dimension of driving inputs. If
TYPE:
|
spectral_radius
|
Target spectral radius for recurrent weights. If
TYPE:
|
bias
|
Whether to include a bias term.
TYPE:
|
bias_scaling
|
Scale of the random bias: entries are drawn from
TYPE:
|
activation
|
Activation function for reservoir dynamics.
TYPE:
|
leak_rate
|
Leaky integration rate in A per-neuron leak rate — a 1-D tensor or sequence of length
TYPE:
|
noise
|
Standard deviation of additive Gaussian state noise injected after the activation, following the classical ESN regularizer (Jaeger 2001; Lukoševičius 2012): \[
\tilde{h}_t = f(\cdot) + \nu\,\epsilon_t,
\quad \epsilon_t \sim \mathcal{N}(0, 1)
\]
where \(\nu\) =
TYPE:
|
trainable
|
If
TYPE:
|
sparse
|
CSR requires a frozen reservoir. Setting Native Erdős–Rényi and edge-native graph initialization avoid a dense
square adjacency. Sparse spectral scaling uses Arnoldi (or analytic
triangular spectra), with a bounded exact fallback only for sizes 1–2;
it raises on failed convergence instead of allocating a dense fallback.
Its numerical scaling can differ from dense eigvals in the last digits.
Custom in-place-only initializers may still need a temporary dense
matrix; override
TYPE:
|
feedback_initializer
|
Initializer for the feedback weight matrix. Accepts a registry
name,
TYPE:
|
input_initializer
|
Initializer for the input weight matrix. Same formats as
TYPE:
|
topology
|
Structure of the recurrent weight matrix: a registry name (graph or
matrix topology), any matrix-building callable, a
TYPE:
|
recurrent_initializer
|
First-class alias for
TYPE:
|
bias_initializer
|
Override the default random bias. Uses the same formats as input
initialization on a
TYPE:
|
initial_state_initializer
|
Initialize a persistent
TYPE:
|
device
|
Device on which parameters are constructed. Defaults to the Torch default device. CUDA initialization runs on the requested device; MPS cells initialize on CPU and move the complete cell afterward, preserving compatibility across supported Torch versions. |
dtype
|
Floating-point initialization precision. Defaults to Torch's default
dtype.
TYPE:
|
seed
|
Reproducibility seed that deterministically fixes every reservoir
parameter — the recurrent (topology) matrix, the feedback and input
weights (including the default |
| ATTRIBUTE | DESCRIPTION |
|---|---|
weight_feedback |
Feedback weight matrix of shape
TYPE:
|
weight_input |
Input weight matrix of shape
TYPE:
|
weight_hh |
Dense Parameter or frozen CSR view of the recurrent weight matrix of shape
TYPE:
|
bias_h |
Bias vector of shape
TYPE:
|
See Also
resdag.layers.esn.ESNLayer : Layer that sequences this cell. resdag.layers.base.ReservoirCell : Abstract cell interface.
Source code in src/resdag/layers/cells/esn_cell.py
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 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 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 | |
leak_rate
property
writable
¶
float or torch.Tensor : Leaky-integration rate(s) read fresh every step.
A live knob: assigning to it (directly or through
ESNLayer.leak_rate = ...) validates the value and takes effect on the
next forward. Returns the scalar float for a homogeneous leak
(1.0 means no leaking, standard ESN) or the (reservoir_size,)
buffer for a per-neuron heterogeneous leak. Every entry stays in
(0, 1].
noise
property
writable
¶
noise: float
float : Std-dev of additive train-mode state noise (>= 0).
A live knob validated on assignment; 0.0 disables noise. Noise is
applied only when the cell is in training mode (see _apply_noise).
trainable
property
writable
¶
trainable: bool
bool : Whether the reservoir weights participate in backpropagation.
This is a live switch, not a construction-time-only flag. Assigning
to it flips requires_grad_ on every cell parameter
(weight_hh, weight_feedback, weight_input, bias_h) so a
post-construction cell.trainable = True genuinely unfreezes the
reservoir for a BPTT rollout — the documented
reservoir.trainable = True recipe now takes effect instead of being
a silent no-op. The getter reflects the current state.
output_size
property
¶
output_size: int
Dimensionality of the per-step output (equals state_size for ESN).
sparse
property
¶
sparse: bool
bool : Whether the CSR sparse recurrent-matmul path is active.
Reflects the resolved decision (after the "auto" density gate and
the frozen-reservoir requirement), not the raw construction request.
False for a dense cell or when sparse="auto" fell back to dense.
spectral_radius_achieved
property
¶
spectral_radius_achieved: float
float : Spectral radius of the effective pre-activation recurrent operator.
Measures diag(intrinsic_gain * recurrent_gain) @ weight_hh when
calibration gains exist, or simply weight_hh for an uncalibrated
cell. Intrinsic plasticity scales both input and recurrent drive;
flow control scales recurrent rows only. Neither additive bias affects
this matrix radius.
This is the linear recurrent operator immediately before the activation,
not the state-dependent tanh derivative or the leaky-update Jacobian.
It therefore does not guarantee stable nonlinear dynamics. The original
spectral_radius remains the requested construction-time value.
Measurement uses the shared estimator; MPS performs its unsupported
eigendecomposition on CPU.
init_state
¶
Return the configured initial state, broadcast independently per batch item.
The optional initializer is sampled once at construction as (1, N)
and saved with the weights. Every reset reuses that same vector.
Source code in src/resdag/layers/cells/esn_cell.py
672 673 674 675 676 677 678 679 680 681 682 683 684 685 | |
forward
¶
Compute the next ESN state for a single timestep.
| PARAMETER | DESCRIPTION |
|---|---|
inputs
|
Per-timestep input slices. |
state
|
Current hidden state of shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
output
|
Next hidden state of shape
TYPE:
|
new_state
|
Same tensor as output (state and output are identical for ESN).
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the feedback feature dimension does not match
|
Notes
When self.noise > 0 and the cell is in training mode, additive
Gaussian noise is injected into the post-activation state (see the
noise constructor parameter). This matches the noise applied in
the step fast path, so the two paths stay consistent.
Source code in src/resdag/layers/cells/esn_cell.py
694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 | |
project_inputs
¶
Precompute all input-dependent pre-activation terms.
Computes W_fb x_fb + W_in x_in + b for every timestep at once.
Works on full (batch, timesteps, features) sequences (the layer's
fast path) and on single-step (batch, features) slices (reused by
forward).
| PARAMETER | DESCRIPTION |
|---|---|
inputs
|
Input streams; |
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Input projection with the same leading dimensions as the inputs
and trailing dimension |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If feature dimensions do not match the cell configuration, or a
driving input is supplied to a cell built without |
Source code in src/resdag/layers/cells/esn_cell.py
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 | |
step
¶
Recurrent-only single-step update for the projected fast path.
addmm fuses the recurrent matmul with the precomputed input
projection into one kernel; with activation and leak that is three
kernel launches per timestep instead of six.
| PARAMETER | DESCRIPTION |
|---|---|
projected_t
|
Slice of
TYPE:
|
state
|
Current hidden state, shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
output
|
Next hidden state.
TYPE:
|
new_state
|
Same tensor as output.
TYPE:
|
Source code in src/resdag/layers/cells/esn_cell.py
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 | |
NGCell
¶
NGCell(
input_dim: int,
k: int = 2,
s: int = 1,
p: int = 2,
cumulative: bool = False,
include_constant: bool = True,
include_linear: bool = True,
)
Bases: ReservoirCell
Single-timestep NG-RC feature construction cell.
This is NOT a recurrent cell — it owns no weight matrices and has no
recurrent dynamics. The "state" is a FIFO delay buffer of the last
(k-1)*s input vectors. The cell wraps feedforward feature
construction (time-delayed inputs + polynomial monomials) behind a
forward(x, state) -> (features, new_state) interface so that it
composes with the same DAG infrastructure as ESNCell.
| PARAMETER | DESCRIPTION |
|---|---|
input_dim
|
Dimensionality of a single input vector.
TYPE:
|
k
|
Number of delay taps (including the current input).
TYPE:
|
s
|
Spacing between delay taps, in timesteps.
TYPE:
|
p
|
Polynomial degree for nonlinear feature construction. See Exact-degree convention ( Cumulative-degree convention ( Note. When
TYPE:
|
cumulative
|
Degree convention for the nonlinear block (see
TYPE:
|
include_constant
|
Whether to prepend a constant
TYPE:
|
include_linear
|
Whether to include the linear delay-embedded features
TYPE:
|
| ATTRIBUTE | DESCRIPTION |
|---|---|
feature_dim |
Total dimension of the output feature vector In the default exact-degree mode (
TYPE:
|
state_size |
Number of rows in the delay buffer:
TYPE:
|
monomial_indices |
Long tensor of shape
TYPE:
|
delay_indices |
Long tensor of shape
TYPE:
|
Examples:
Basic usage (k=2, s=1, p=2):
>>> cell = NGCell(input_dim=3)
>>> x = torch.randn(4, 3) # (batch=4, d=3)
>>> state = cell.init_state(4, x.device, x.dtype) # (4, 1, 3)
>>> features, new_state = cell([x], state)
>>> features.shape
torch.Size([4, 28])
>>> new_state.shape
torch.Size([4, 1, 3])
No-delay mode (k=1):
>>> cell = NGCell(input_dim=3, k=1)
>>> state = cell.init_state(1, 'cpu', torch.float32)
>>> features, new_state = cell([torch.randn(1, 3)], state)
>>> features.shape
torch.Size([1, 10])
See Also
resdag.layers.reservoirs.ngrc.NGReservoirLayer : Sequence wrapper for this cell.
Source code in src/resdag/layers/cells/ngrc_cell.py
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 | |
init_state
¶
Return a zero-filled initial delay buffer.
| PARAMETER | DESCRIPTION |
|---|---|
batch_size
|
Number of samples in the batch.
TYPE:
|
device
|
Target device for the buffer. |
dtype
|
Target dtype for the buffer.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Zero tensor of shape |
Source code in src/resdag/layers/cells/ngrc_cell.py
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 | |
forward
¶
Compute the NG-RC feature vector for a single timestep.
| PARAMETER | DESCRIPTION |
|---|---|
inputs
|
Per-timestep input slices. |
state
|
Delay buffer of shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
features
|
Output feature vector
TYPE:
|
new_state
|
Updated delay buffer of shape
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Source code in src/resdag/layers/cells/ngrc_cell.py
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 422 423 424 425 426 427 428 429 430 431 | |
forward_sequence
¶
Compute NG-RC features for a whole sequence in a single vectorized pass.
This is the batch-forward fast path used by
resdag.layers.reservoirs.ngrc.NGReservoirLayer.forward. It is
numerically identical to scanning forward step-by-step
(0.0 max-abs-diff, including the warmup region), but contains no
per-timestep Python loop: the delay-embedded linear features are built
from shifted, front-zero-padded slices of the input, every monomial is
gathered over the full (batch, timesteps, *) tensor at once, and the
constant-ones block is allocated a single time.
| PARAMETER | DESCRIPTION |
|---|---|
x
|
Input sequence of shape
TYPE:
|
state
|
Incoming delay buffer of shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
features
|
Output features
TYPE:
|
new_state
|
Updated delay buffer of shape
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
See Also
NGCell.forward : Single-step counterpart driving the streaming path.
Source code in src/resdag/layers/cells/ngrc_cell.py
468 469 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 | |
validate_state
¶
validate_state(state: Tensor) -> None
Validate the 3-D delay-buffer layout used by NG-RC.
| PARAMETER | DESCRIPTION |
|---|---|
state
|
Candidate state of shape
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Source code in src/resdag/layers/cells/ngrc_cell.py
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 | |
ES2NCell
¶
Bases: _SkipReservoirCell
Single-timestep Edge-of-Stability State Network (ES2N) update.
ES2N (Ceni & Gallicchio, arXiv:2308.02902) reconciles the Echo State
Property with long memory by writing the reservoir state as a **convex
combination** of a standard nonlinear ESN branch and a linear, input-free
*orthogonal* branch. Its update (paper Eq. 5, adapted to resdag's separate
feedback / driving-input streams) is
$$
x_t = \beta\,\phi(W_r x_{t-1} + W_{fb} x_{fb,t} + W_{in} u_t + b)
+ (1 - \beta)\,O\,x_{t-1}
$$
where $\phi$ is the activation, $O$ is a **fixed random
orthogonal** matrix (the skip / residual branch), $W_r$ is the
spectral-radius-scaled frozen recurrent matrix, $W_{fb}$ / $W_{in}$
the feedback / input weights, $b$ the random bias, and
$\beta \in (0, 1]$ the *proximity* hyperparameter.
The paper folds the feedback into the input term $u_t$; resdag keeps
feedback and driving inputs as separate projections, so the projectable
input part is $W_{fb} x_{fb,t} + W_{in} u_t + b$ and the recurrent
part is $W_r x_{t-1}$ (inside $\phi$) plus $O x_{t-1}$
(the skip).
Interpretation of `beta`:
* $\beta \to 0$ — the map approaches the orthogonal, norm-preserving
linear map $x_t \approx O x_{t-1}$. All Jacobian eigenvalues hover
on the complex unit circle: the *edge of stability*, giving very long
(near-lossless) memory (paper Thm. 3.5).
* $\beta = 1$ — the skip vanishes and the update reduces to a standard
**non-leaky** ESN $x_t = \phi(W_r x_{t-1} + \cdots)$.
Because the proximity plays the memory-timescale role a leaky ESN gives to
its leak rate, ES2N takes **no** `leak_rate` argument (and no train-mode
`noise`, which is not part of the ES2N formulation).
Parameters
Parameters
reservoir_size, feedback_size, input_size, spectral_radius, bias, \
bias_scaling, activation, trainable, feedback_initializer, input_initializer, \
topology, orthogonal_scaling, seed
See resdag.layers.cells._skip_cell._SkipReservoirCell and
resdag.layers.cells.esn_cell.ESNCell for the shared meanings.
beta : float, default=0.9
Proximity to the edge of stability, in \((0, 1]\). Smaller values
weight the orthogonal skip more heavily (longer memory, closer to the
edge of chaos); 1.0 recovers a standard non-leaky ESN. A live
knob validated on assignment (like a leak rate): cell.beta = ...
takes effect on the next forward.
Attributes
Attributes
skip_matrix : torch.Tensor
Frozen orthogonal skip matrix `O` (see the base class).
weight_hh, weight_feedback, weight_input, bias_h
Recurrent, feedback, input weights and bias (see
`resdag.layers.cells.esn_cell.ESNCell`).
Examples
Examples
>>> import torch
>>> cell = ES2NCell(reservoir_size=64, feedback_size=3, beta=0.1)
>>> state = cell.init_state(2, torch.device("cpu"), torch.float32)
>>> out, new_state = cell([torch.randn(2, 3)], state)
>>> out.shape
torch.Size([2, 64])
See Also
See Also
resdag.layers.reservoirs.es2n.ES2NLayer : Layer that sequences this cell.
resdag.layers.cells.resesn_cell.ResESNCell : Decoupled-weight variant.
Source code in src/resdag/layers/cells/es2n_cell.py
102 103 104 105 106 107 108 109 110 111 112 113 114 115 | |
beta
property
writable
¶
beta: float
float : Proximity to the edge of stability, in \((0, 1]\).
A live knob: assigning to it (directly or through
ES2NLayer.beta = ...) validates the value and takes effect on the
next forward. beta near 0 weights the orthogonal skip (long memory,
edge of stability); beta = 1 recovers a standard non-leaky ESN.
ResESNCell
¶
ResESNCell(
reservoir_size: int,
feedback_size: int,
alpha: float = 0.5,
beta: float = 0.9,
**kwargs: object
)
Bases: _SkipReservoirCell
Single-timestep Residual Echo State Network (ResESN) update.
ResESN (Ceni & Gallicchio, 2024) generalises ES2N by **decoupling** the
skip and nonlinear branch weights: where ES2N ties them into a convex
combination $(1 - \beta,\ \beta)$, ResESN gives each branch an
independent scaling coefficient. Its shallow-model update (Eq. 2 of
arXiv:2508.21172, adapted to resdag's separate feedback / driving-input
streams) is
$$
x_t = \alpha\,O\,x_{t-1}
+ \beta\,\phi(W_r x_{t-1} + W_{fb} x_{fb,t} + W_{in} u_t + b)
$$
where $\phi$ is the activation, $O$ a **fixed random
orthogonal** matrix (the residual branch), $W_r$ the
spectral-radius-scaled frozen recurrent matrix, $W_{fb}$ /
$W_{in}$ the feedback / input weights, $b$ the random bias, and
$\alpha$ (skip) and $\beta$ (nonlinear) the two independent
scaling coefficients that replace the leaky-integrator leak rate.
Relationship to other models:
* $\alpha = 1 - \beta$ recovers **ES2N** (the convex combination).
* $O = I$ with $1 - \alpha = \beta$ recovers a **leaky ESN**.
Like ES2N, ResESN takes **no** `leak_rate` (the two branch weights
subsume it) and no train-mode `noise` (not part of the formulation).
Parameters
Parameters
reservoir_size, feedback_size, input_size, spectral_radius, bias, \
bias_scaling, activation, trainable, feedback_initializer, input_initializer, \
topology, orthogonal_scaling, seed
See resdag.layers.cells._skip_cell._SkipReservoirCell and
resdag.layers.cells.esn_cell.ESNCell for the shared meanings.
alpha : float, default=0.5
Scaling coefficient of the orthogonal skip (residual) branch. Must be
finite. Larger values weight the linear memory branch more heavily; the
Echo State Property holds under a contractivity condition analogous to a
standard ESN's (see the paper). A live knob validated on assignment.
beta : float, default=0.9
Scaling coefficient of the nonlinear branch. Must be finite. A live
knob validated on assignment.
Attributes
Attributes
skip_matrix : torch.Tensor
Frozen orthogonal skip matrix `O` (see the base class).
weight_hh, weight_feedback, weight_input, bias_h
Recurrent, feedback, input weights and bias (see
`resdag.layers.cells.esn_cell.ESNCell`).
Examples
Examples
>>> import torch
>>> cell = ResESNCell(reservoir_size=64, feedback_size=3, alpha=0.6, beta=0.4)
>>> state = cell.init_state(2, torch.device("cpu"), torch.float32)
>>> out, new_state = cell([torch.randn(2, 3)], state)
>>> out.shape
torch.Size([2, 64])
See Also
See Also
resdag.layers.reservoirs.resesn.ResESNLayer : Layer that sequences this cell.
resdag.layers.cells.es2n_cell.ES2NCell : Convex-combination (ES2N) variant.
Source code in src/resdag/layers/cells/resesn_cell.py
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 | |
GatedReservoirCell
¶
GatedReservoirCell(
reservoir_size: int,
feedback_size: int,
input_size: int | None = None,
spectral_radius: float | None = None,
bias: bool = True,
bias_scaling: float = 1.0,
update_gate_bias: float = 2.0,
activation: str = "relu",
gate_activation: str = "sigmoid",
trainable: bool = False,
feedback_initializer: InitializerSpec = None,
input_initializer: InitializerSpec = None,
topology: TopologySpec = None,
seed: SeedLike = None,
*,
recurrent_initializer: TopologySpec = None,
bias_initializer: InitializerSpec = None,
initial_state_initializer: InitializerSpec = None,
device: device | str | None = None,
dtype: dtype | None = None,
gate_recurrent_initializer: TopologySpec = None,
gate_feedback_initializer: InitializerSpec = None,
gate_input_initializer: InitializerSpec = None,
gate_bias_initializer: InitializerSpec = None,
gate_spectral_radius: float | None = None
)
Bases: ReservoirCell
Single-timestep frozen light-gated (LiGRU) reservoir update — a reservoir GRU.
Owns all weight matrices and biases; frozen by default
(trainable=False), like a classical ESN, so only a downstream readout is
fitted. Sequence iteration is delegated to the enclosing
resdag.layers.reservoirs.gated.GatedReservoirLayer.
The update is a reservoir adaptation of the Light Gated Recurrent Unit (Ravanelli et al. 2018):
where \(u_t = W_{fb}\,x_{fb,t} + W_{in}\,x_{in,t}\) is the drive
(feedback plus optional driving input, projected exactly as in
ESNCell), \(\sigma\) is the sigmoid update-gate nonlinearity,
and \(\phi\) is the candidate nonlinearity ("relu" by default, the
LiGRU choice). z gates retention: z→1 keeps h, z→0 writes
the candidate.
Stability of a frozen gated reservoir
A frozen random GRU can saturate — a random update-gate pre-activation
centred at 0 gives z ≈ 0.5, which over-writes the state every step
and washes out memory (or, with an unfortunate draw, drives h to a
constant). Two knobs keep it well-behaved:
update_gate_bias(default2.0) biases the update gate toward retention:b_z = update_gate_biasmakeszstart nearσ(2) ≈ 0.88, so a fresh reservoir keeps most of its state each step and the dynamics do not collapse. This mirrors the classic "initialise the forget-gate bias positive" trick for trainable gated RNNs.spectral_radiusscales the recurrent candidate weight \(W_{hh}\) (via the shared resdag machinery), controlling the echo of past state through the candidate path just as it does for an ESN.
Even so, a frozen gated reservoir often underperforms a plain ESN; the
gated cell is usually most useful with trainable=True (a BPTT rollout
that updates the gates), which this cell fully supports via the base
trainable property.
| PARAMETER | DESCRIPTION |
|---|---|
reservoir_size
|
Number of reservoir units (hidden state dimension
TYPE:
|
feedback_size
|
Dimension of the feedback signal. Required.
TYPE:
|
input_size
|
Dimension of an optional driving input. If
TYPE:
|
spectral_radius
|
Target spectral radius for the recurrent candidate weight
\(W_{hh}\). If
TYPE:
|
bias
|
Whether to include gate biases (
TYPE:
|
bias_scaling
|
Scale of the random candidate bias
TYPE:
|
update_gate_bias
|
Constant added to the update-gate pre-activation (the value of
TYPE:
|
activation
|
Candidate nonlinearity \(\phi\).
TYPE:
|
gate_activation
|
Update-gate nonlinearity \(\sigma\).
TYPE:
|
trainable
|
If
TYPE:
|
feedback_initializer
|
Initializer for the feedback weight matrix (drive path). Same accepted
forms as
TYPE:
|
input_initializer
|
Initializer for the driving-input weight matrix. Only used when
TYPE:
|
topology
|
Structure of the recurrent candidate weight \(W_{hh}\). The
recurrent gate weights
TYPE:
|
seed
|
Reproducibility seed for independent weight, bias and reset-state roles.
Integers and a generator's |
recurrent_initializer
|
First-class alias for
TYPE:
|
bias_initializer
|
Input/feedback initializer grammar applied to a
TYPE:
|
initial_state_initializer
|
Initializes a persistent
TYPE:
|
device
|
Initial parameter location. Metal construction initializes on CPU before transferring to support initialization operations across backends. |
dtype
|
Floating precision used during initialization, not only after conversion.
TYPE:
|
gate_recurrent_initializer
|
Separate recurrent gate matrix. Defaults to small dense random weights.
TYPE:
|
gate_spectral_radius
|
Outer radius target for the gate recurrence, respecting its scaling policy.
TYPE:
|
gate_feedback_initializer
|
Separate gate projections. Omitted projections share candidate weights.
A driver gate initializer requires
TYPE:
|
gate_input_initializer
|
Separate gate projections. Omitted projections share candidate weights.
A driver gate initializer requires
TYPE:
|
gate_bias_initializer
|
Gate-bias initializer on
TYPE:
|
| ATTRIBUTE | DESCRIPTION |
|---|---|
weight_feedback |
Feedback drive weight
TYPE:
|
weight_input |
Driving-input drive weight
TYPE:
|
weight_hh |
Recurrent candidate weight \(W_{hh}\) of shape
TYPE:
|
weight_hz |
Recurrent update-gate weight \(W_{hz}\) of shape
TYPE:
|
bias_h |
Candidate bias
TYPE:
|
bias_z |
Update-gate bias
TYPE:
|
See Also
resdag.layers.reservoirs.gated.GatedReservoirLayer : Layer that sequences this cell. resdag.layers.cells.esn_cell.ESNCell : Ungated ESN cell. resdag.layers.cells.base_cell.ReservoirCell : Abstract cell interface.
Source code in src/resdag/layers/cells/gated_cell.py
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 422 423 424 425 426 427 428 429 430 431 | |
trainable
property
writable
¶
trainable: bool
bool : Whether the reservoir weights participate in backpropagation.
A live switch: assigning to it flips requires_grad_ on every
cell parameter, so cell.trainable = True genuinely unfreezes the
gated reservoir for a BPTT rollout (identical semantics to
ESNCell).
state_size
property
¶
state_size: int
Packed state width: n_state_tensors * hidden_size.
For this single-state (GRU) cell that is just hidden_size; the
multiplication documents the packed convention for future multi-state
cells (see the module docstring).
gate_activation
property
¶
gate_activation: str
str : Name of the update-gate activation function \(\sigma\).
spectral_radius_achieved
property
¶
spectral_radius_achieved: float
float : Realized largest absolute eigenvalue of the candidate W_hh.
init_state
¶
Return a zero packed state of shape (batch_size, state_size).
Source code in src/resdag/layers/cells/gated_cell.py
492 493 494 495 496 497 498 499 500 501 502 503 504 505 | |
forward
¶
Compute the next gated state for a single timestep.
| PARAMETER | DESCRIPTION |
|---|---|
inputs
|
|
state
|
Current packed state of shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
output
|
Next hidden state
TYPE:
|
new_state
|
Next packed state (identical to
TYPE:
|
Source code in src/resdag/layers/cells/gated_cell.py
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 | |
project_inputs
¶
Precompute the input drive u = W_fb x_fb + W_in x_in for the sequence.
This is the sequence-precomputable part of the gated update — it does
not include the gate biases or the recurrent terms, which depend on
the (per-step) state. Works on both full
(batch, timesteps, features) sequences (the layer fast path) and
single-step (batch, features) slices (reused by forward).
| PARAMETER | DESCRIPTION |
|---|---|
inputs
|
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Drive |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
On a feedback/driving-input feature-dimension mismatch, or if a
driving input is supplied to a cell built without |
Source code in src/resdag/layers/cells/gated_cell.py
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 | |
step
¶
Single-step gated update consuming a slice of project_inputs.
Shape-static and branch-free (both gates are σ / φ of tensors),
so it traces cleanly under torch.compile(fullgraph=True) for the
compiled forecast engine.
| PARAMETER | DESCRIPTION |
|---|---|
projected_t
|
Per-timestep drive
TYPE:
|
state
|
Current packed state
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
output
|
Next hidden state
TYPE:
|
new_state
|
Next packed state (identical to
TYPE:
|
Source code in src/resdag/layers/cells/gated_cell.py
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 | |
ContinuousReservoirCell
¶
ContinuousReservoirCell(
reservoir_size: int,
feedback_size: int,
input_size: int | None = None,
spectral_radius: float | None = None,
bias: bool = True,
bias_scaling: float = 1.0,
activation: str = "tanh",
trainable: bool = False,
dt: float = 1.0,
substeps: int = 1,
solver: str = "euler",
torchdiffeq_method: str = "dopri5",
rtol: float = 1e-06,
atol: float = 1e-08,
feedback_initializer: InitializerSpec = None,
input_initializer: InitializerSpec = None,
topology: TopologySpec = None,
seed: SeedLike = None,
*,
recurrent_initializer: TopologySpec = None,
bias_initializer: InitializerSpec = None,
initial_state_initializer: InitializerSpec = None,
device: device | str | None = None,
dtype: dtype | None = None
)
Bases: ESNCell
Abstract base for reservoir cells that integrate $\dot h = f(h, u)$.
Extends `resdag.layers.cells.esn_cell.ESNCell` with fixed-step ODE
integration over each input interval. Concrete subclasses implement only
`vector_field` (the $\dot h = f(h, u)$ term); this base supplies
the sub-stepping (`step`), the input projection (inherited
`ESNCell.project_inputs`), and the sequence-level `forward`.
The state update integrates one input interval — one timestep of the driving
sequence — with `substeps` fixed sub-steps of size `dt / substeps`,
holding the projected input drive $u$ constant across the interval
(zero-order hold). Writing $g = \text{dt}/\text{substeps}$ for the
sub-step size, one **Euler** sub-step is
$$
h \leftarrow h + g \, f(h, u),
$$
and one classical **RK4** sub-step is the usual four-stage weighted average.
The recurrent / feedback / input weights, bias, spectral scaling and
freezing are all owned and initialized by `ESNCell`.
Parameters
Parameters
reservoir_size, feedback_size, input_size, spectral_radius, bias, \
bias_scaling, activation, trainable, feedback_initializer, input_initializer, \
topology, seed
Identical in meaning to resdag.layers.cells.esn_cell.ESNCell
(see its docstring). leak_rate and noise are intentionally
absent — the ODE integration replaces leaky integration, and train-mode
state noise is not part of the continuous-cell formulation.
dt : float, default=1.0
Length of one input interval in integration time. The forward-Euler
step size of the Euler State Network is dt with substeps=1.
substeps : int, default=1
Number of fixed integration sub-steps per input interval. Each has size
dt / substeps. More sub-steps integrate the same interval more
accurately; 1 is the single-step form used by EuSN.
solver : {'euler', 'rk4', 'torchdiffeq'}, default='euler'
Integration scheme. 'euler' and 'rk4' are fixed-step, need no
extra dependency, and trace fullgraph=True under
torch.compile. 'torchdiffeq' uses an adaptive solver over
each interval (zero-order-hold input) and requires the optional
resdag[ode] extra; it may not compile fullgraph=True.
torchdiffeq_method : str, default='dopri5'
Adaptive method passed to torchdiffeq.odeint when
solver='torchdiffeq'. Ignored otherwise.
rtol, atol : float, default=1e-6, 1e-8
Relative / absolute tolerances for the torchdiffeq adaptive solver.
Ignored by the fixed-step solvers.
recurrent_initializer : spec, optional
First-class alias for `topology`. Supply one spelling only. Names,
tuples, callables and registered initializer objects are accepted.
bias_initializer : spec, optional
Input/feedback initializer grammar applied to a `(1, reservoir_size)`
view of the bias. Requires `bias=True`; overrides `bias_scaling`.
initial_state_initializer : spec, optional
Initializes a persistent `(1, cell.state_size)` reset template once.
Each batch example receives an independent copy at reset. Zero by default.
device : torch.device or str, optional
Initial parameter location. Metal construction initializes on CPU before
transferring to support initialization operations across backends.
dtype : torch.dtype, optional
Floating precision used during initialization, not only after conversion.
Attributes
Attributes
dt : float
Input-interval length (integration time).
substeps : int
Fixed sub-steps per interval.
solver : str
Active solver name.
weight_hh, weight_feedback, weight_input, bias_h
Recurrent, feedback, input weights and bias (see
`resdag.layers.cells.esn_cell.ESNCell`).
Notes
Notes
`vector_field` receives the **precomputed** input drive `projected_u`
(`W_fb x_fb + W_in u + b` for this interval), held constant across every
sub-step — the caller does the projection once per interval, so the field
itself only mixes in the recurrent / diffusion term that depends on `h`.
See Also
See Also
resdag.layers.cells.eusn_cell.EuSNCell : Concrete Euler State Network cell.
resdag.layers.cells.esn_cell.ESNCell : The leaky-ESN cell this base extends.
Source code in src/resdag/layers/cells/continuous_cell.py
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 | |
dt
property
writable
¶
dt: float
Positive, finite integration interval; changes apply to the next step.
vector_field
abstractmethod
¶
Return the ODE right-hand side \(\dot h = f(h, u)\) for one interval.
Called once per integration sub-step with the same projected_u
(zero-order hold across the interval). The input drive is already
projected (W_fb x_fb + W_in u + b), so the field only adds the
recurrent / diffusion term that depends on state.
| PARAMETER | DESCRIPTION |
|---|---|
state
|
Current reservoir state, shape
TYPE:
|
projected_u
|
Precomputed input drive for this interval, shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The time derivative \(\dot h\), shape |
Source code in src/resdag/layers/cells/continuous_cell.py
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 | |
output_from_state
¶
Map the integrated state to the readable per-step output.
Defaults to the identity (output == state), matching ESNCell.
Subclasses whose readable output differs from the raw state override
this.
| PARAMETER | DESCRIPTION |
|---|---|
state
|
Integrated reservoir state, shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Per-step output, shape |
Source code in src/resdag/layers/cells/continuous_cell.py
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 | |
forward
¶
Integrate one input interval and return (output, new_state).
Projects the per-step inputs (W_fb x_fb + W_in u + b) and integrates
the vector field over one interval of length dt.
| PARAMETER | DESCRIPTION |
|---|---|
inputs
|
|
state
|
Current reservoir state, shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
output
|
Per-step output
TYPE:
|
new_state
|
Integrated reservoir state
TYPE:
|
Source code in src/resdag/layers/cells/continuous_cell.py
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 | |
step
¶
Integrate one interval from a precomputed projection slice.
Consumes projected_t (W_fb x_fb + W_in u + b for this interval)
and integrates the vector field over one interval. For the fixed-step
solvers the sub-step loop is static, so this traces cleanly under
torch.compile (fullgraph=True), enabling the compiled
forecast / teacher-forced engines.
| PARAMETER | DESCRIPTION |
|---|---|
projected_t
|
Slice of
TYPE:
|
state
|
Current reservoir state, shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
output
|
Per-step output
TYPE:
|
new_state
|
Integrated reservoir state
TYPE:
|
Source code in src/resdag/layers/cells/continuous_cell.py
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 | |
EuSNCell
¶
EuSNCell(
reservoir_size: int,
feedback_size: int,
epsilon: float = 0.01,
gamma: float = 0.01,
input_size: int | None = None,
spectral_radius: float | None = None,
bias: bool = True,
bias_scaling: float = 1.0,
activation: str = "tanh",
substeps: int = 1,
solver: str = "euler",
torchdiffeq_method: str = "dopri5",
rtol: float = 1e-06,
atol: float = 1e-08,
trainable: bool = False,
feedback_initializer: InitializerSpec = None,
input_initializer: InitializerSpec = None,
topology: TopologySpec = None,
seed: SeedLike = None,
*,
recurrent_initializer: TopologySpec = None,
bias_initializer: InitializerSpec = None,
initial_state_initializer: InitializerSpec = None,
device: device | str | None = None,
dtype: dtype | None = None
)
Bases: ContinuousReservoirCell
Single-timestep Euler State Network (EuSN) update.
EuSN (Gallicchio, arXiv:2203.09382) models the reservoir as an ODE
$$
\dot h(t) = \tanh\!\big(W_h\, h(t) + W_x\, x(t) + b\big),
$$
with $W_h$ **antisymmetric** ($W_h = -W_h^\top$), and integrates
it with a single forward-Euler step of size $\varepsilon$, subtracting
a small **diffusion** term $\gamma I$ from the recurrence for numerical
stability:
$$
h_t = h_{t-1} + \varepsilon\,
\tanh\!\big((W_h - \gamma I)\, h_{t-1} + W_x\, x_t + b\big).
$$
The antisymmetric $W_h$ is a rotation generator (purely imaginary
eigenvalues), so $x \mapsto W_h x$ conserves the state norm; a small
Euler step of the resulting flow is therefore **near-norm-preserving** — a
stable, non-dissipative, long-memory regime with local Lyapunov exponents
near zero (the "edge of stability"). The diffusion $\gamma I$ adds a
tiny contraction that damps the forward-Euler discretization error and keeps
the recurrence from drifting outward over long sequences.
resdag construction
resdag construction
resdag keeps feedback and driving inputs as *separate* projections, so the
paper's $W_x x_t + b$ maps to resdag's precomputed drive
$W_{fb} x_{fb,t} + W_{in} u_t + b$ (the inherited
`resdag.layers.cells.esn_cell.ESNCell.project_inputs`). The
antisymmetric $W_h$ is obtained **on the fly** from the frozen,
spectral-radius-scaled recurrent matrix `weight_hh` (`= W_r`) as
$W_r - W_r^\top$; the stored `W_r` is left untouched (cleaner than
baking antisymmetry into the buffer, and matching the paper's constraint
exactly). The vector field is therefore
$$
f(h, u) = \tanh\!\big((W_r - W_r^\top - \gamma I)\, h + u\big),
$$
with $u$ the precomputed drive and one Euler sub-step of size
$\varepsilon$ (`dt=epsilon`, `substeps=1`).
Because the antisymmetric part $W_r - W_r^\top$ has purely imaginary
eigenvalues, a layer-level `spectral_radius` on `W_r` still controls the
*rotation rate* of the recurrence (the largest imaginary eigenvalue
magnitude), so the usual scaling knob remains meaningful.
Parameters
Parameters
reservoir_size, feedback_size, input_size, bias, bias_scaling, activation, \
trainable, feedback_initializer, input_initializer, topology, seed
See resdag.layers.cells.esn_cell.ESNCell. activation
defaults to "tanh" (the EuSN nonlinearity); other activations are
accepted for experimentation.
epsilon : float, default=0.01
Forward-Euler step size \(\varepsilon\). Small values sit the
reservoir near the edge of stability (near-norm-preserving); the paper
sweeps \(\varepsilon \in \{10^{-5}, \dots, 1\}\). Stored as the
base dt.
gamma : float, default=0.01
Diffusion coefficient \(\gamma \ge 0\) subtracted as \(\gamma I\)
from the antisymmetric recurrence. A small positive value damps the
Euler discretization error; 0.0 recovers the purely norm-preserving
(undamped) antisymmetric flow. A live knob validated on assignment.
spectral_radius : float, optional
Target rotation rate of the effective antisymmetric operator
\(W_r - W_r^\top\) — its largest |imaginary eigenvalue|, the
quantity that actually drives the dynamics — not the raw W_r.
W_r is rescaled so the skew part hits this radius (see the notes on
antisymmetric scaling below). None leaves W_r unscaled.
substeps : int, default=1
Fixed integration sub-steps per interval (see
ContinuousReservoirCell). 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' integrate the same vector field more
accurately (they agree with Euler in the small-epsilon limit).
recurrent_initializer : spec, optional
First-class alias for `topology`. Supply one spelling only. Names,
tuples, callables and registered initializer objects are accepted.
bias_initializer : spec, optional
Input/feedback initializer grammar applied to a `(1, reservoir_size)`
view of the bias. Requires `bias=True`; overrides `bias_scaling`.
initial_state_initializer : spec, optional
Initializes a persistent `(1, cell.state_size)` reset template once.
Each batch example receives an independent copy at reset. Zero by default.
device : torch.device or str, optional
Initial parameter location. Metal construction initializes on CPU before
transferring to support initialization operations across backends.
dtype : torch.dtype, optional
Floating precision used during initialization, not only after conversion.
Attributes
Attributes
gamma : float
Diffusion coefficient (live knob).
epsilon : float
Euler step size (alias of `dt`).
weight_hh, weight_feedback, weight_input, bias_h
Recurrent (`W_r`), feedback, input weights and bias (see
`resdag.layers.cells.esn_cell.ESNCell`).
Examples
Examples
>>> import torch
>>> cell = EuSNCell(reservoir_size=64, feedback_size=3, epsilon=0.01, gamma=0.01)
>>> state = cell.init_state(2, torch.device("cpu"), torch.float32)
>>> out, new_state = cell([torch.randn(2, 3)], state)
>>> out.shape
torch.Size([2, 64])
See Also
See Also
resdag.layers.reservoirs.eusn.EuSNLayer : Layer that sequences this cell.
resdag.layers.cells.continuous_cell.ContinuousReservoirCell : Integration base.
resdag.layers.cells.esn_cell.ESNCell : Standard leaky-ESN cell.
Source code in src/resdag/layers/cells/eusn_cell.py
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 | |
gamma
property
writable
¶
gamma: float
float : Diffusion coefficient \(\gamma \ge 0\).
A live knob: assigning to it (directly or through
EuSNLayer.gamma = ...) validates the value and takes effect on the
next forward. 0.0 recovers the undamped antisymmetric flow.
epsilon
property
writable
¶
epsilon: float
float : Forward-Euler step size \(\varepsilon\) (alias of dt).
vector_field
¶
EuSN field \(\tanh\big((W_r - W_r^\top - \gamma I)\,h + u\big)\).
Antisymmetrizes the frozen recurrent matrix on the fly
(\(W_r - W_r^\top\)), subtracts the diffusion \(\gamma I\), adds
the precomputed input drive projected_u, and applies the activation
(tanh by default).
| PARAMETER | DESCRIPTION |
|---|---|
state
|
Current state
TYPE:
|
projected_u
|
Precomputed input drive
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
\(\dot h\), shape |
Source code in src/resdag/layers/cells/eusn_cell.py
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 | |
SpikingReservoirCell
¶
SpikingReservoirCell(
reservoir_size: int,
v_threshold: float = 1.0,
reset: str = "subtract",
surrogate_beta: float = 10.0,
trace_decay: float = 0.9,
output: str = "trace",
)
Bases: ReservoirCell, ABC
Abstract base for spiking reservoir cells (the LSM substrate).
Owns the machinery shared by every spiking neuron model — the packed
multi-tensor state, the surrogate-gradient spike, the spike reset, and the
low-pass readout trace — and delegates only the sub-threshold membrane
dynamics to a concrete subclass through neuron_update.
Packed state layout
A spiking cell carries several (batch, reservoir_size) state tensors,
packed side-by-side into one 2-D (batch, n_state_tensors * reservoir_size)
tensor (the convention documented in
resdag.layers.cells.gated_cell). The layout is fixed by the
subclass via n_state_tensors; the last packed block is always the
synaptic trace r (owned by this base), and the leading blocks are the
subclass's neuron state, which ends with the previous step's spikes s
(the recurrent input) — e.g. V then s, or I, V then s.
Concretely:
- first-order LIF (
n_state_tensors= 3):[V | s | r]; - CuBa-LIF (
n_state_tensors= 4):[I | V | s | r].
neuron_update receives / returns only the neuron tensors (all but
the trace); the base peels the trace off before the call and re-appends the
updated trace after, so a subclass never handles the trace. Because those
neuron tensors end with s, the membrane potential V is the
second-to-last neuron tensor — this is what output="voltage" returns.
The surrogate-gradient spike
spike implements the straight-through estimator: an exact Heaviside
forward with a fast-sigmoid surrogate backward (slope surrogate_beta).
Subclasses call it from neuron_update to emit spikes from the
(updated) membrane potential.
| PARAMETER | DESCRIPTION |
|---|---|
reservoir_size
|
Number of spiking units (hidden dimension of each packed state tensor).
TYPE:
|
v_threshold
|
Firing threshold \(V_\text{th}\). A neuron spikes when its membrane potential crosses this value from below.
TYPE:
|
reset
|
Membrane reset on a spike.
TYPE:
|
surrogate_beta
|
Slope \(\beta\) of the fast-sigmoid surrogate \(\sigma(\beta (V - V_\text{th}))\) used for the straight-through backward pass. Larger values sharpen the surrogate toward the true (non-differentiable) step; the default follows common SNN practice.
TYPE:
|
trace_decay
|
Decay \(\kappa \in [0, 1)\) of the low-pass readout trace
\(r_t = \kappa\, r_{t-1} + s_t\). The trace is the cell's readable
output (a real-valued filtered spike response).
TYPE:
|
output
|
Which quantity
TYPE:
|
| ATTRIBUTE | DESCRIPTION |
|---|---|
reservoir_size |
Hidden dimension of each packed state tensor.
TYPE:
|
v_threshold |
Firing threshold.
TYPE:
|
surrogate_beta |
Surrogate slope (live knob).
TYPE:
|
trace_decay |
Readout-trace decay (live knob).
TYPE:
|
Notes
Refractoriness is intentionally not modelled in this first version: a
refractory counter is integer-valued and its "is the neuron clamped?" branch
is data-dependent, which fights torch.compile(fullgraph=True) and the
surrogate-gradient flow. It is deferred as future work rather than shipped
fragile; the soft/hard reset already yields the regular-spiking f–I behaviour
a Liquid State Machine relies on.
See Also
resdag.layers.cells.lif_cell.LIFCell : Concrete leaky integrate-and-fire cell. resdag.layers.cells.base_cell.ReservoirCell : Abstract cell interface.
Source code in src/resdag/layers/cells/spiking_cell.py
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 | |
surrogate_beta
property
writable
¶
surrogate_beta: float
float : Fast-sigmoid surrogate slope \(\beta > 0\) (live knob).
trace_decay
property
writable
¶
trace_decay: float
float : Readout-trace decay \(\kappa \in [0, 1)\) (live knob).
n_neuron_tensors
property
¶
n_neuron_tensors: int
Number of neuron state tensors (packed state minus the trace).
state_size
property
¶
state_size: int
Packed state width: n_state_tensors * reservoir_size.
Includes the trailing synaptic-trace block owned by this base, so a
first-order LIF (n_state_tensors == 2) has state_size == 2 * reservoir_size and a CuBa-LIF (3) has 3 * reservoir_size.
output_size
property
¶
output_size: int
Dimensionality of the per-step readable output (reservoir_size).
init_state
¶
Return a zero packed state of shape (batch_size, state_size).
Source code in src/resdag/layers/cells/spiking_cell.py
261 262 263 264 265 266 267 268 | |
spike
¶
Surrogate-gradient spike from a membrane potential (straight-through).
Forward is the exact Heaviside threshold (v - V_th > 0); backward
flows through the fast-sigmoid surrogate
\(\sigma(\beta (v - V_\text{th}))\). The
surrogate + (hard - surrogate).detach() construction makes the
returned tensor equal hard in value while carrying the surrogate's
gradient — a pure composition of tensor ops (no custom
torch.autograd.Function), so it traces fullgraph=True.
| PARAMETER | DESCRIPTION |
|---|---|
v
|
Membrane potential, shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Binary spike tensor (values in |
Source code in src/resdag/layers/cells/spiking_cell.py
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 | |
apply_reset
¶
Reset the membrane potential on the neurons that just spiked.
'subtract' (soft): \(V \leftarrow V - V_\text{th}\,s\) — keeps the
supra-threshold overshoot, the standard LIF reset. 'zero' (hard):
\(V \leftarrow V (1 - s)\) — clamps the membrane to zero on a spike.
The branch is a Python attribute compare fixed at construction, so it is
static under torch.compile.
| PARAMETER | DESCRIPTION |
|---|---|
v
|
Post-integration membrane potential, shape
TYPE:
|
spikes
|
Spike tensor from
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The reset membrane potential. |
Source code in src/resdag/layers/cells/spiking_cell.py
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 | |
update_trace
¶
Low-pass the spike train into the readout trace.
\(r_t = \kappa\, r_{t-1} + s_t\) with \(\kappa\) = trace_decay.
The trace is the real-valued synaptic response a readout regresses on.
| PARAMETER | DESCRIPTION |
|---|---|
trace
|
Previous trace
TYPE:
|
spikes
|
Current spikes
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Updated trace |
Source code in src/resdag/layers/cells/spiking_cell.py
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 | |
neuron_update
abstractmethod
¶
neuron_update(
neuron_state: tuple[Tensor, ...], projected_input: Tensor
) -> tuple[tuple[Tensor, ...], Tensor]
Advance the sub-threshold dynamics one step and emit spikes.
Called by step with the neuron state tensors only (the trailing
trace is peeled off by the base) and the precomputed input drive. The
subclass integrates its membrane / current dynamics, emits spikes via the
shared spike helper, applies the reset via apply_reset,
and returns the updated neuron tensors together with the spikes.
| PARAMETER | DESCRIPTION |
|---|---|
neuron_state
|
The
TYPE:
|
projected_input
|
Precomputed input drive (recurrent-spike + feedback + driver + bias
excluding the recurrent term, which the subclass adds from the
previous spikes it keeps in state — see
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
new_neuron_state
|
The updated neuron tensors in the same packing order.
TYPE:
|
spikes
|
The binary spike tensor emitted this step, shape
TYPE:
|
Source code in src/resdag/layers/cells/spiking_cell.py
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 | |
project_inputs
abstractmethod
¶
Precompute the per-step input drive for the sequence.
Concrete spiking cells own the feedback / input / bias weights, so the
projection lives on the subclass (mirrors
resdag.layers.cells.esn_cell.ESNCell.project_inputs).
Source code in src/resdag/layers/cells/spiking_cell.py
396 397 398 399 400 401 402 403 404 | |
forward
¶
Advance one timestep: project inputs, then step.
| PARAMETER | DESCRIPTION |
|---|---|
inputs
|
|
state
|
Current packed state
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
output
|
Readable per-step output
TYPE:
|
new_state
|
Updated packed state
TYPE:
|
Source code in src/resdag/layers/cells/spiking_cell.py
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 | |
step
¶
Single-step spiking update from a precomputed input drive.
Peels the trailing trace r off the packed state, hands the neuron
tensors + drive to neuron_update, low-passes the returned spikes
into the new trace, and re-packs. Branch-free apart from the static
reset / output selection, so it traces fullgraph=True for the
compiled forecast / teacher-forced engines.
| PARAMETER | DESCRIPTION |
|---|---|
projected_t
|
Precomputed input drive for this step, shape
TYPE:
|
state
|
Current packed state
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
output
|
Readable per-step output
TYPE:
|
new_state
|
Updated packed state
TYPE:
|
Source code in src/resdag/layers/cells/spiking_cell.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 465 466 467 468 469 470 471 472 473 474 475 476 477 | |
LIFCell
¶
LIFCell(
reservoir_size: int,
feedback_size: int,
input_size: int | 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,
output: str = "trace",
spectral_radius: float | None = None,
bias: bool = True,
bias_scaling: float = 1.0,
trainable: bool = False,
feedback_initializer: InitializerSpec = None,
input_initializer: InitializerSpec = None,
topology: TopologySpec = None,
seed: SeedLike = None,
*,
recurrent_initializer: TopologySpec = None,
bias_initializer: InitializerSpec = None,
initial_state_initializer: InitializerSpec = None,
device: device | str | None = None,
dtype: dtype | None = None
)
Bases: SpikingReservoirCell
Single-timestep leaky integrate-and-fire (LIF) reservoir cell.
Owns the frozen recurrent weight W_rec (topology-initialised and
spectral-radius scaled like an ESN), the feedback / driving-input weights and
the bias. The sub-threshold dynamics are a discretised leaky integrator; the
surrogate spike, reset, and readout trace are inherited from
resdag.layers.cells.spiking_cell.SpikingReservoirCell.
| PARAMETER | DESCRIPTION |
|---|---|
reservoir_size
|
Number of spiking units.
TYPE:
|
feedback_size
|
Dimension of the feedback signal. Required.
TYPE:
|
input_size
|
Dimension of an optional driving input.
TYPE:
|
tau_mem
|
Membrane time constant \(\tau_\text{mem} > 0\) (same time units as
TYPE:
|
tau_syn
|
Synaptic time constant \(\tau_\text{syn} > 0\). Only used when
TYPE:
|
dt
|
Integration timestep \(\Delta t > 0\).
TYPE:
|
synaptic_current
|
If
TYPE:
|
v_threshold
|
Firing threshold (see
TYPE:
|
reset
|
Membrane reset on a spike (see
TYPE:
|
surrogate_beta
|
Fast-sigmoid surrogate slope for the straight-through spike gradient.
TYPE:
|
trace_decay
|
Decay of the low-pass readout trace (the cell's real-valued output).
TYPE:
|
output
|
Readable-output mode.
TYPE:
|
spectral_radius
|
Target spectral radius for
TYPE:
|
bias
|
Whether to include a bias current
TYPE:
|
bias_scaling
|
Scale of the random bias (
TYPE:
|
trainable
|
If
TYPE:
|
feedback_initializer
|
Initializers for the feedback / driving-input weights. Same accepted
forms as
TYPE:
|
input_initializer
|
Initializers for the feedback / driving-input weights. Same accepted
forms as
TYPE:
|
topology
|
Structure of the recurrent weight
TYPE:
|
seed
|
Reproducibility seed for independent weight, bias and reset-state roles.
Integers and a generator's |
recurrent_initializer
|
First-class alias for
TYPE:
|
bias_initializer
|
Input/feedback initializer grammar applied to a
TYPE:
|
initial_state_initializer
|
Initializes a persistent
TYPE:
|
device
|
Initial parameter location. Metal construction initializes on CPU before transferring to support initialization operations across backends. |
dtype
|
Floating precision used during initialization, not only after conversion.
TYPE:
|
| ATTRIBUTE | DESCRIPTION |
|---|---|
beta |
Membrane decay \(\beta = e^{-\Delta t/\tau_\text{mem}}\) (derived).
TYPE:
|
alpha |
Synaptic-current decay \(\alpha = e^{-\Delta t/\tau_\text{syn}}\)
(derived; only meaningful when
TYPE:
|
weight_rec |
Recurrent spike-coupling weight
TYPE:
|
weight_feedback |
Feedback weight
TYPE:
|
weight_input |
Driving-input weight
TYPE:
|
bias_h |
Bias current
TYPE:
|
Examples:
>>> import torch
>>> cell = LIFCell(reservoir_size=64, feedback_size=3, tau_mem=20.0, seed=0)
>>> state = cell.init_state(2, torch.device("cpu"), torch.float32)
>>> out, new_state = cell([torch.randn(2, 3)], state)
>>> out.shape
torch.Size([2, 64])
See Also
resdag.layers.cells.spiking_cell.SpikingReservoirCell : Shared spiking base. resdag.layers.reservoirs.lif.LIFReservoirLayer : Layer that sequences this cell.
Source code in src/resdag/layers/cells/lif_cell.py
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 | |
tau_mem
property
writable
¶
tau_mem: float
Live membrane time constant; updates recompute both decays.
tau_syn
property
writable
¶
tau_syn: float
Live synaptic time constant; updates recompute both decays.
trainable
property
writable
¶
trainable: bool
bool : Whether the reservoir weights participate in backpropagation.
A live switch: assigning to it flips requires_grad_ on every
cell parameter (weight_rec, weight_feedback, weight_input,
bias_h). With the surrogate-gradient spike this genuinely unfreezes
the LIF reservoir for a BPTT rollout.
spectral_radius_achieved
property
¶
spectral_radius_achieved: float
float : Realized largest absolute eigenvalue of weight_rec.
init_state
¶
Initialize packed neuron and trace state; zero by default.
Source code in src/resdag/layers/cells/lif_cell.py
359 360 361 362 363 364 365 366 367 | |
project_inputs
¶
Precompute the analog input drive W_fb x_fb + W_in u + b.
This is the input-dependent part of the neuron drive — the recurrent
spike term W_rec s is added inside neuron_update from the
previous spikes carried in state. Works on full
(batch, timesteps, features) sequences (the layer fast path) and on
single-step (batch, features) slices.
| PARAMETER | DESCRIPTION |
|---|---|
inputs
|
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Input drive with the inputs' leading dims and trailing dimension
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
On a feedback / driving-input feature-dimension mismatch, or if a
driving input is supplied to a cell built without |
Source code in src/resdag/layers/cells/lif_cell.py
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 | |
neuron_update
¶
neuron_update(
neuron_state: tuple[Tensor, ...], projected_input: Tensor
) -> tuple[tuple[Tensor, ...], Tensor]
Advance the LIF (or CuBa-LIF) membrane one step and emit spikes.
The recurrent spike term \(W_\text{rec} s_t\) is added here (from the
previous spikes s carried in neuron_state), completing the drive
projected_input + W_rec s. Branch-free apart from the static
synaptic_current / reset selection, so it traces fullgraph=True.
| PARAMETER | DESCRIPTION |
|---|---|
neuron_state
|
TYPE:
|
projected_input
|
Precomputed analog drive
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
new_neuron_state
|
TYPE:
|
spikes
|
The spikes emitted this step (
TYPE:
|
Source code in src/resdag/layers/cells/lif_cell.py
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 | |
CoRNNCell
¶
CoRNNCell(
reservoir_size: int,
feedback_size: int,
input_size: int | None = None,
*,
dt: float = 0.1,
gamma: float = 1.0,
epsilon: float = 1.0,
recurrent_initializer: RecurrentInitializerSpec = None,
velocity_initializer: RecurrentInitializerSpec = None,
topology: TopologySpec = None,
spectral_radius: float | None = None,
feedback_initializer: InitializerSpec = None,
input_initializer: InitializerSpec = None,
bias: bool = True,
bias_scaling: float = 1.0,
trainable: bool = False,
seed: SeedLike = None,
device: device | str | None = None,
dtype: dtype | None = None
)
Bases: ProjectedInputCell
Coupled nonlinear oscillators, frozen by default.
Uses the explicit-damping variant of equation (3) in the coRNN paper:
v_new = v + dt * (tanh(W_hh h + W_hv v + W_fb x + W_in u + b)
- gamma*h - epsilon*v)
h_new = h + dt * v_new
The packed state is cat([h, v], -1) with width 2*reservoir_size;
the output is position h_new with width reservoir_size.
recurrent_initializer configures the position matrix weight_hh;
velocity_initializer configures the velocity matrix weight_hv.
spectral_radius scales only the position matrix, respecting a builder's
rescaling policy. It does not guarantee stability of the oscillator update.
dt, gamma and epsilon are finite positive/nonnegative scalars.
Both recurrent matrices default to uniform(-1/sqrt(size), 1/sqrt(size)).
Input projections default to uniform(-1, 1). Weights are initialized directly
in dtype on device (MPS initializes on CPU then transfers once). trainable=True enables ordinary backpropagation.
Reference: https://arxiv.org/abs/2010.00951
Source code in src/resdag/layers/cells/cornn_cell.py
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 | |
step
¶
Return updated positions and packed position/velocity state for one frame.
Source code in src/resdag/layers/cells/cornn_cell.py
165 166 167 168 169 170 171 172 | |
LegendreDelayCell
¶
LegendreDelayCell(
order: int,
feedback_size: int,
input_size: int | None = None,
*,
theta: float = 100.0,
dt: float = 1.0,
memory_channels: int | None = None,
feedback_initializer: InitializerSpec = None,
input_initializer: InitializerSpec = None,
trainable: bool = False,
seed: SeedLike = None,
device: device | str | None = None,
dtype: dtype | None = None
)
Bases: ProjectedInputCell
Linear Legendre delay network (LDN), rather than a full nonlinear LMU.
Implements equations (1), (2), and (4) of Voelker et al., NeurIPS 2019.
The analytic continuous matrices are fixed buffers, with theta already
divided into continuous_A and continuous_B. An augmented matrix
exponential computes exact zero-order-hold A/B for interval dt;
no matrix inverse or Euler approximation is used.
order is the number of Legendre coefficients per channel.
memory_channels=None uses feedback_size + (input_size or 0) channels,
one for each input dimension; their default encoders concatenate the raw
feedback and driver. When channels equal that sum, identity encoders are
also used by default. Other channel counts use random linear encoders with
uniform bounds 1/sqrt(total input width). Explicit feedback/input
initializer specs override the respective encoder.
State and output both have width memory_channels * order. They flatten
(batch, memory_channels, order) in channel-major order. theta is a
memory window in the same time units as dt (default dt=1 means samples).
trainable=True trains only input encoders; the memory dynamics stay fixed.
The linear memory should be followed by nonlinear features/model components
when the task needs nonlinear predictions.
The scaled continuous matrix 1-norm must not exceed 2**20; extreme
dt/theta ratios or orders beyond this numerical bound are rejected
before exponentiation. MPS construction initializes on CPU then moves once.
Source code in src/resdag/layers/cells/legendre_delay_cell.py
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 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 | |
step
¶
Advance one zero-order-hold interval and return readable and carried memory.
Source code in src/resdag/layers/cells/legendre_delay_cell.py
194 195 196 197 198 199 200 | |
TorchRecurrentCell
¶
TorchRecurrentCell(
cell: GRUCell | LSTMCell,
feedback_size: int,
input_size: int | None = None,
*,
trainable: bool = False
)
Bases: ReservoirCell
Use an existing nn.GRUCell or nn.LSTMCell in a ResDAG graph.
Deep-copies the supplied standard cell, preserving its parameters, device,
and dtype. trainable=False freezes the copy; the caller's cell is never
changed. Its input_size must equal feedback_size + (input_size or 0).
Inputs are ordered feedback then optional driver. LSTM state is packed
cat([h, c], -1) of width 2*hidden_size; GRU state is h. Both
expose only h as output. This permits imported/pretrained cells and
ordinary gradient training without requiring a separate RNN implementation.
Input gate projections are batched across the entire sequence; recurrent updates implement the documented PyTorch equations, including GRU's reset gate placement around the hidden new-gate projection and its bias. A frozen GRU/LSTM is not guaranteed to have the echo state property.
References: https://docs.pytorch.org/docs/stable/generated/torch.nn.GRUCell.html and https://docs.pytorch.org/docs/stable/generated/torch.nn.LSTMCell.html
Source code in src/resdag/layers/cells/torch_recurrent_cell.py
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | |
trainable
property
writable
¶
trainable: bool
Whether the copied native cell's parameters receive gradients.
state_size
property
¶
state_size: int
Carried width: hidden state for GRU, packed hidden/carry state for LSTM.
output_size
property
¶
output_size: int
Hidden-state width, equal to the supplied native cell's hidden_size.
init_state
¶
Return zero initial hidden state, including LSTM carry when applicable.
Source code in src/resdag/layers/cells/torch_recurrent_cell.py
79 80 81 | |
project_inputs
¶
Project feedback and optional driver into the native cell's input gates.
Source code in src/resdag/layers/cells/torch_recurrent_cell.py
83 84 85 86 87 88 | |
step
¶
Advance one projected frame and return hidden output and carried state.
Source code in src/resdag/layers/cells/torch_recurrent_cell.py
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 | |
forward
¶
Advance one raw feedback/driver frame using the native GRU/LSTM equations.
Source code in src/resdag/layers/cells/torch_recurrent_cell.py
119 120 121 | |
Sequence layers¶
BaseReservoirLayer owns sequence iteration, reset and carried-state behavior.
Its forward_stateless and step_stateless return explicit recurrent state
without changing stored state. Concrete layers inherit that contract; common
inherited Torch methods are not repeated below. Use ordinary to, train,
eval, hooks and state dictionaries as for any nn.Module.
reservoirs
¶
ESNLayer
¶
ESNLayer(
reservoir_size: int,
feedback_size: int,
input_size: int | None = None,
spectral_radius: float | None = None,
bias: bool = True,
bias_scaling: float = 1.0,
activation: str = "tanh",
leak_rate: float | Tensor | Sequence[float] = 1.0,
noise: float = 0.0,
trainable: bool = False,
sparse: SparseSpec = False,
feedback_initializer: InitializerSpec = None,
input_initializer: InitializerSpec = None,
topology: TopologySpec = None,
seed: SeedLike = None,
*,
recurrent_initializer: TopologySpec = None,
bias_initializer: InitializerSpec = None,
initial_state_initializer: InitializerSpec = None,
device: device | str | None = None,
dtype: dtype | None = None
)
Bases: BaseReservoirLayer
Stateful RNN reservoir layer for Echo State Networks.
Public-facing class. Internally creates an ESNCell that owns
all parameters and performs the single-step update; the sequence loop
and state management live in the parent BaseReservoirLayer.
| PARAMETER | DESCRIPTION |
|---|---|
reservoir_size
|
Number of reservoir units (hidden state dimension).
TYPE:
|
feedback_size
|
Dimension of feedback signal. Required for all reservoirs.
TYPE:
|
input_size
|
Dimension of driving inputs. If
TYPE:
|
spectral_radius
|
Target spectral radius for recurrent weights. Controls the
"memory" and stability of the reservoir. If
TYPE:
|
bias
|
Whether to include a bias term.
TYPE:
|
bias_scaling
|
Scale of the random bias: entries are drawn from
TYPE:
|
activation
|
Activation function for reservoir dynamics.
TYPE:
|
leak_rate
|
Leaky integration rate in
TYPE:
|
noise
|
Standard deviation of additive Gaussian state noise injected after the
activation (the classical ESN readout-conditioning regularizer).
Active only in training mode (like dropout) and a no-op under
TYPE:
|
trainable
|
If
TYPE:
|
sparse
|
TYPE:
|
feedback_initializer
|
Initializer for the feedback weight matrix. Accepts a registry
name,
TYPE:
|
input_initializer
|
Initializer for the input weight matrix. Same formats as
TYPE:
|
topology
|
Structure of the recurrent weight matrix. Accepts a registry name
(graph or matrix topology),
TYPE:
|
recurrent_initializer
|
First-class alias for
TYPE:
|
bias_initializer
|
Override the default random bias. Uses the same formats as input
initialization on a
TYPE:
|
initial_state_initializer
|
Initialize a persistent
TYPE:
|
device
|
Device on which parameters are constructed. Defaults to the Torch default device. CUDA initialization runs on the requested device; MPS cells initialize on CPU and move the complete cell afterward, preserving compatibility across supported Torch versions. |
dtype
|
Floating-point initialization precision. Defaults to Torch's default
dtype.
TYPE:
|
seed
|
Reproducibility seed that deterministically fixes the entire
reservoir — topology (recurrent) matrix, feedback weights, input
weights, and bias — so two layers built with the same seed are
identical down to the last entry. Accepts a plain |
| ATTRIBUTE | DESCRIPTION |
|---|---|
state |
Current reservoir state of shape
TYPE:
|
Examples:
Basic feedback-only reservoir:
>>> reservoir = ESNLayer(reservoir_size=500, feedback_size=10)
>>> feedback = torch.randn(4, 50, 10) # (batch, time, features)
>>> output = reservoir(feedback)
>>> print(output.shape)
torch.Size([4, 50, 500])
Reservoir with driving input:
>>> reservoir = ESNLayer(
... reservoir_size=500,
... feedback_size=10,
... input_size=5,
... spectral_radius=0.95
... )
>>> feedback = torch.randn(4, 50, 10)
>>> driving = torch.randn(4, 50, 5)
>>> output = reservoir(feedback, driving)
Using graph topology by name:
>>> reservoir = ESNLayer(
... reservoir_size=500,
... feedback_size=10,
... topology="erdos_renyi",
... spectral_radius=0.9
... )
Using topology with custom parameters (tuple format):
>>> reservoir = ESNLayer(
... reservoir_size=500,
... feedback_size=10,
... topology=("watts_strogatz", {"k": 6, "p": 0.3}),
... feedback_initializer=("pseudo_diagonal", {"input_scaling": 0.5}),
... spectral_radius=0.95
... )
Fully reproducible reservoir via the seed argument — recurrent matrix,
feedback/input weights, and bias all match:
>>> a = ESNLayer(50, feedback_size=3, topology="erdos_renyi", seed=42)
>>> b = ESNLayer(50, feedback_size=3, topology="erdos_renyi", seed=42)
>>> torch.equal(a.weight_hh, b.weight_hh)
True
>>> torch.equal(a.weight_feedback, b.weight_feedback)
True
>>> torch.equal(a.bias_h, b.bias_h)
True
A torch.Generator works too (e.g. an HPO per-trial generator):
>>> g1 = torch.Generator().manual_seed(7)
>>> g2 = torch.Generator().manual_seed(7)
>>> a = ESNLayer(50, feedback_size=3, seed=g1)
>>> b = ESNLayer(50, feedback_size=3, seed=g2)
>>> torch.equal(a.weight_feedback, b.weight_feedback)
True
The reservoir is also reproducible under torch.manual_seed without an
explicit seed:
>>> torch.manual_seed(0)
>>> a = ESNLayer(50, feedback_size=3, topology="erdos_renyi")
>>> torch.manual_seed(0)
>>> b = ESNLayer(50, feedback_size=3, topology="erdos_renyi")
>>> torch.equal(a.weight_hh, b.weight_hh)
True
Stateful processing across batches:
>>> out1 = reservoir(data1) # State initialized
>>> out2 = reservoir(data2) # State carries over
>>> reservoir.reset_state() # Manual reset
>>> out3 = reservoir(data3) # Fresh state
See Also
resdag.layers.cells.esn_cell.ESNCell : Underlying single-step cell. resdag.layers.reservoirs.base_reservoir.BaseReservoirLayer : Base providing state management. resdag.init.topology.TopologyInitializer : Base class for topology init. resdag.init.input_feedback.InputFeedbackInitializer : Input init base. resdag.core.ESNModel : Model composition using reservoir layers.
Source code in src/resdag/layers/reservoirs/esn.py
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 | |
BaseReservoirLayer
¶
BaseReservoirLayer(cell: ReservoirCell)
Abstract base that owns the sequence loop and all state-management methods.
Subclasses create a ReservoirCell and pass it to this
constructor. The sequence loop (iterating over timesteps and calling the
cell) lives here; the cell handles the per-step computation.
| PARAMETER | DESCRIPTION |
|---|---|
cell
|
Concrete cell instance that performs the single-step update.
TYPE:
|
| ATTRIBUTE | DESCRIPTION |
|---|---|
cell |
The wrapped single-step cell.
TYPE:
|
state |
Current reservoir state, or
TYPE:
|
detach_state_between_calls |
If
TYPE:
|
See Also
resdag.layers.esn.ESNLayer : Concrete ESN layer built on this base. resdag.layers.base.ReservoirCell : Abstract cell interface.
Source code in src/resdag/layers/reservoirs/base_reservoir.py
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 | |
forward_stateless
¶
forward_stateless(
inputs: list[Tensor], state: Tensor, *, compile: bool = False
) -> tuple[Tensor, Tensor]
Run the time loop purely: thread state in and out, touch no self state.
This is the functional core of the reservoir. It takes the initial
state as an explicit argument, threads it through the per-timestep
loop, and returns the per-step outputs together with the final state.
It never reads or writes state, performs no in-place tensor
writes (per-step outputs are collected with torch.stack), and
the loop body contains no data-dependent Python branch. Those three
properties are what make it torch.compile-scan, torch.func.vmap,
and TorchScript/ONNX-export friendly, unlike the stateful
forward wrapper that drives it.
| PARAMETER | DESCRIPTION |
|---|---|
inputs
|
Feedback tensor first, then at most one driving-input tensor, each
of shape |
state
|
Initial reservoir state, shape
TYPE:
|
compile
|
Opt-in compiled/chunked engine for the teacher-forced sequence loop
(warmup, The compiled path is inference-only: it transparently falls back
to the eager loop when any parameter, input projection, or initial
state requires grad (a differentiable BPTT rollout must stay eager),
when there is no projected fast path
(e.g. NG-RC), on |
| RETURNS | DESCRIPTION |
|---|---|
outputs
|
Per-step outputs, shape
TYPE:
|
new_state
|
Final reservoir state after the last timestep.
TYPE:
|
Notes
The cross-call detach applied by forward (truncated BPTT) lives
in that wrapper, outside this method — gradients flow through the
returned new_state here, so callers that backpropagate through state
carried across calls are free to do so.
Source code in src/resdag/layers/reservoirs/base_reservoir.py
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 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 | |
step_stateless
¶
Single-timestep analogue of forward_stateless: state in, state out.
Where forward_stateless consumes whole
(batch, timesteps, features) sequences and runs the time loop, this
consumes a single (batch, features) slice per stream and performs
exactly one cell update. It is the per-step primitive that the
flattened autoregressive engine
(resdag.core.ESNModel.forecast) drives, sidestepping the
sequence-loop bookkeeping (torch.stack, shape[1] reads) that
forward / forward_stateless pay even for a length-1
sequence.
| PARAMETER | DESCRIPTION |
|---|---|
inputs
|
Feedback slice first, then at most one driving-input slice, each of
shape |
state
|
Current reservoir state, shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
output
|
Per-step output, shape
TYPE:
|
new_state
|
Updated reservoir state.
TYPE:
|
Notes
The project-vs-fallback choice is the same per-cell static decision made
in forward_stateless (no data-dependent branch in the hot path),
so this method stays torch.compile-fullgraph friendly. Like
forward_stateless it never reads or writes state, and it
applies no cross-call detach — the forecast engine runs under
torch.no_grad, so the threaded state never carries a graph.
Source code in src/resdag/layers/reservoirs/base_reservoir.py
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 | |
forward
¶
Process an input sequence through the reservoir.
Computes reservoir states for each timestep using the feedback
signal and optional driving inputs. This is a thin stateful wrapper
over the pure forward_stateless: it validates inputs, lazily
initialises state, runs the functional loop, stores the
returned state, and applies the cross-call detach.
| PARAMETER | DESCRIPTION |
|---|---|
feedback
|
Feedback signal of shape
TYPE:
|
*driving_inputs
|
Optional driving input of shape
TYPE:
|
compile
|
Route the teacher-forced sequence loop through the opt-in
compiled/chunked engine. Forwarded verbatim to
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Reservoir states for all timesteps, shape
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Notes
The layer maintains internal state across forward calls. Use
reset_state to clear the state between independent sequences.
For a pure, self-free variant (used by the compile-scan, vmap, and
export paths) call forward_stateless directly.
Source code in src/resdag/layers/reservoirs/base_reservoir.py
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 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 | |
reference_device_dtype
¶
Resolve the canonical device and dtype of this reservoir's weights.
The reference is the first floating-point parameter or buffer of the
inner cell (the same scan used when lazily allocating a zero state),
falling back to cpu / float32 for weightless cells such as the
NG-RC reservoir. This is the device/dtype an incoming forward pass is
expected to use, so callers restoring a saved state should coerce it to
this reference to avoid a silent re-initialisation in
_maybe_init_state.
| RETURNS | DESCRIPTION |
|---|---|
device
|
Device of the cell's first floating-point tensor, or
TYPE:
|
dtype
|
Dtype of the cell's first floating-point tensor, or
TYPE:
|
Source code in src/resdag/layers/reservoirs/base_reservoir.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 848 849 850 851 | |
reset_state
¶
reset_state(batch_size: int | None = None) -> None
Reset internal state to zero.
| PARAMETER | DESCRIPTION |
|---|---|
batch_size
|
If provided, initialize state with this batch size using the
cell's device and dtype. If
TYPE:
|
Examples:
>>> layer.reset_state() # Lazy initialization
>>> layer.reset_state(batch_size=4) # Explicit zero state
Source code in src/resdag/layers/reservoirs/base_reservoir.py
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 | |
get_state
¶
get_state() -> Tensor | None
Get a copy of the current internal state.
| RETURNS | DESCRIPTION |
|---|---|
Tensor or None
|
Clone of the current state tensor, or |
Examples:
>>> state = layer.get_state()
>>> if state is not None:
... print(f"State shape: {state.shape}")
Source code in src/resdag/layers/reservoirs/base_reservoir.py
881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 | |
set_state
¶
set_state(state: Tensor) -> None
Set the internal state to a specific tensor.
Validation is delegated to self.cell.validate_state(state) so
each cell type owns its own state-shape contract (2-D for ESNCell,
3-D delay buffer for NGCell, etc.).
Batch-size contract
The restored state's batch size (state.shape[0]) pins the batch size
the next forward pass must use. A restored state is treated as
deliberate: if a subsequent forward is called with a different batch
size, _maybe_init_state raises a RuntimeError instead of
silently zero-reinitialising and discarding the state you restored. To
forecast at a different batch size, restore (or reset_state and
re-warm) a state of the matching batch size; to opt back into automatic
batch-size re-initialisation, call reset_state. Device and dtype
are not pinned — the state moves with the module under .to() and is
cast to match an incoming forward.
Autograd contract
The stored state honours detach_state_between_calls, exactly as
the cross-call truncated-BPTT detach in forward does. Under the
default (True) a restored state is treated as a fresh initial
condition: it is stored as state.detach().clone() so it carries no
grad_fn and a later forward + backward cannot try to backprop
through state's already-freed graph (the "backward through the graph
a second time" / retained-memory failure that
detach_state_between_calls exists to prevent). Set
detach_state_between_calls=False to store state.clone() with its
graph intact, when you intentionally backprop through state carried in
across calls (and manage the retained graph yourself).
| PARAMETER | DESCRIPTION |
|---|---|
state
|
New state tensor. Its batch size (
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the cell's |
See Also
reset_state : Clear the state and opt back into automatic batch-size re-initialisation.
Examples:
>>> saved = layer.get_state() # captured at batch size B
>>> # ... process data ...
>>> layer.set_state(saved) # next forward must also use batch B
Source code in src/resdag/layers/reservoirs/base_reservoir.py
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 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 | |
set_random_state
¶
set_random_state(
batch_size: int | None = None,
device: device | None = None,
dtype: dtype | None = None,
) -> None
Set the internal state to random (standard-normal) values.
| PARAMETER | DESCRIPTION |
|---|---|
batch_size
|
If provided, lazily initialise the state with this batch size
before filling it with random values. Uses
TYPE:
|
device
|
Target device when lazily initialising. Ignored if the state is already initialised.
TYPE:
|
dtype
|
Target dtype when lazily initialising. Ignored if the state is already initialised.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
RuntimeError
|
If the state has not been initialised and |
Examples:
>>> # Lazy: initialise then randomise in one call
>>> layer.set_random_state(batch_size=4)
>>> # Already-initialised state: just randomise in place
>>> layer.set_random_state()
Source code in src/resdag/layers/reservoirs/base_reservoir.py
986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 | |
NGReservoirLayer
¶
NGReservoirLayer(
input_dim: int,
k: int = 2,
s: int = 1,
p: int = 2,
cumulative: bool = False,
include_constant: bool = True,
include_linear: bool = True,
)
Bases: BaseReservoirLayer
Stateful sequence layer for Next Generation Reservoir Computing.
Wraps NGCell and processes a full input sequence by scanning
causally over the time axis, maintaining an internal FIFO delay buffer as
state.
This is a feedforward feature map — there are no recurrent weight matrices and no learnable parameters. Gradients flow through it to upstream modules if needed.
| PARAMETER | DESCRIPTION |
|---|---|
input_dim
|
Dimensionality of each input vector.
TYPE:
|
k
|
Number of delay taps (including current input).
TYPE:
|
s
|
Spacing between delay taps, in timesteps.
TYPE:
|
p
|
Polynomial degree for nonlinear feature construction. By default
(
TYPE:
|
cumulative
|
Degree convention for the nonlinear block.
TYPE:
|
include_constant
|
Whether to prepend a constant
TYPE:
|
include_linear
|
Whether to include the linear delay-embedded features in the output.
TYPE:
|
| ATTRIBUTE | DESCRIPTION |
|---|---|
cell |
The inner single-step cell.
TYPE:
|
state |
Current delay buffer of shape
TYPE:
|
Notes
The delay buffer needs warmup_length = (k-1)*s steps to fill. Steps
before that produce valid features, but those features contain zeros from
unfilled buffer slots. The layer returns all steps; the caller can discard
the first warmup_length outputs if desired.
State management is inherited from BaseReservoirLayer with the
exception of set_state, which is overridden to validate the 3-D
buffer shape (batch, state_size, input_dim).
Examples:
Basic usage:
>>> layer = NGReservoirLayer(input_dim=3)
>>> x = torch.randn(4, 100, 3) # (batch=4, seq_len=100, d=3)
>>> features = layer(x)
>>> features.shape
torch.Size([4, 100, 28])
Double-scroll configuration (odd-symmetry, Eq. 10):
>>> layer = NGReservoirLayer(
... input_dim=2, k=2, s=1, p=3,
... include_constant=False, include_linear=True
... )
>>> x = torch.randn(1, 50, 2)
>>> features = layer(x)
>>> features.shape
torch.Size([1, 50, 24])
See Also
resdag.layers.cells.ngrc_cell.NGCell : The wrapped single-step cell. resdag.layers.reservoirs.base_reservoir.BaseReservoirLayer : Base class. resdag.layers.readouts.cg_readout.CGReadoutLayer : Algebraic readout.
Source code in src/resdag/layers/reservoirs/ngrc.py
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 | |
warmup_length
property
¶
warmup_length: int
Number of timesteps required to fill the delay buffer.
Steps before this index contain zeros from unfilled buffer slots.
Outputs are still produced for all timesteps; the caller may discard
the first warmup_length outputs if needed.
forward_stateless
¶
forward_stateless(
inputs: list[Tensor], state: Tensor, *, compile: bool = False
) -> tuple[Tensor, Tensor]
Pure whole-sequence NG-RC feature map: thread state in and out.
Overrides the per-step loop of
resdag.layers.reservoirs.base_reservoir.BaseReservoirLayer.forward_stateless
with the vectorized
resdag.layers.cells.ngrc_cell.NGCell.forward_sequence, which
builds every delay-embedded and monomial feature in one pass. Like the
base method it never reads or writes state and contains no
per-timestep Python loop or data-dependent branch, so it slots into the
compile-scan / vmap / export paths.
| PARAMETER | DESCRIPTION |
|---|---|
inputs
|
|
state
|
Incoming delay buffer of shape
TYPE:
|
compile
|
Accepted for signature parity with the base layer's opt-in compiled teacher-forced scan, but a no-op here: NG-RC is a vectorized feedforward feature map with no per-step recurrent loop to compile.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
outputs
|
NG-RC features for all timesteps, shape
TYPE:
|
new_state
|
Updated delay buffer of shape
TYPE:
|
Source code in src/resdag/layers/reservoirs/ngrc.py
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 | |
forward
¶
Process an input sequence through the NG-RC feature map in one pass.
NG-RC is a feedforward map, so the whole sequence is vectorized: there
is no per-timestep Python loop on this path. The output is
numerically identical to scanning the cell step-by-step (0.0
max-abs-diff, including the warmup region); the per-step
resdag.layers.cells.ngrc_cell.NGCell.forward is retained for
streaming / stateful use and continues seamlessly after a batch call.
This is a thin stateful wrapper over the pure
forward_stateless, mirroring the base layer.
| PARAMETER | DESCRIPTION |
|---|---|
feedback
|
Input sequence of shape
TYPE:
|
*driving_inputs
|
Rejected. NG-RC is a weightless feedforward feature map with no
input weight matrix, so it cannot consume driving inputs. Passing
any raises
TYPE:
|
compile
|
Accepted for signature parity with the base layer but a no-op: NG-RC has no per-step recurrent loop, so there is nothing to compile.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
NG-RC features for all timesteps, shape
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Notes
The layer maintains internal state across forward calls (the FIFO delay
buffer). Use reset_state to clear it between independent
sequences. As in the base class, the stored state is detached from the
autograd graph at call boundaries when
detach_state_between_calls is True (truncated BPTT).
Source code in src/resdag/layers/reservoirs/ngrc.py
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 | |
NGReservoir
¶
Bases: NGReservoirLayer
Deprecated alias for NGReservoirLayer.
Retained for backward compatibility. Instantiating this class emits a
DeprecationWarning and constructs an NGReservoirLayer;
the two are otherwise identical (NGReservoir is a subclass, so
isinstance(NGReservoir(...), NGReservoirLayer) holds).
Deprecated.
Use NGReservoirLayer instead. NGReservoir will be removed
in a future release.
See Also
NGReservoirLayer : The canonical class this aliases.
Source code in src/resdag/layers/reservoirs/ngrc.py
335 336 337 338 339 340 341 342 | |
ES2NLayer
¶
ES2NLayer(
reservoir_size: int,
feedback_size: int,
beta: float = 0.9,
input_size: int | None = None,
spectral_radius: float | None = None,
bias: bool = True,
bias_scaling: float = 1.0,
activation: str = "tanh",
orthogonal_scaling: float = 1.0,
trainable: bool = False,
feedback_initializer: InitializerSpec = None,
input_initializer: InitializerSpec = None,
topology: TopologySpec = None,
seed: SeedLike = None,
*,
recurrent_initializer: TopologySpec = None,
bias_initializer: InitializerSpec = None,
initial_state_initializer: InitializerSpec = None,
device: device | str | None = None,
dtype: dtype | None = None
)
Bases: BaseReservoirLayer
Stateful Edge-of-Stability State Network (ES2N) reservoir layer.
Public-facing class. Internally creates an
resdag.layers.cells.es2n_cell.ES2NCell that owns all parameters
and performs the single-step update; the sequence loop and state management
live in the parent resdag.layers.reservoirs.base_reservoir.BaseReservoirLayer.
ES2N (Ceni & Gallicchio, arXiv:2308.02902) writes the state as a convex combination of a nonlinear ESN branch and a fixed random orthogonal skip:
with \(\beta \in (0, 1]\) the proximity to the edge of stability. Small \(\beta\) → nearly the orthogonal norm-preserving map (long memory, edge of chaos); \(\beta = 1\) → a standard non-leaky ESN.
| PARAMETER | DESCRIPTION |
|---|---|
reservoir_size
|
Number of reservoir units (hidden-state dimension).
TYPE:
|
feedback_size
|
Dimension of the feedback signal. Required.
TYPE:
|
beta
|
Proximity to the edge of stability in \((0, 1]\) (see
TYPE:
|
input_size
|
Dimension of a driving input.
TYPE:
|
spectral_radius
|
Target spectral radius for the recurrent matrix
TYPE:
|
bias
|
Whether to include a bias term.
TYPE:
|
bias_scaling
|
Scale of the random bias (
TYPE:
|
activation
|
Activation for the nonlinear branch.
TYPE:
|
orthogonal_scaling
|
Gain on the orthogonal skip matrix
TYPE:
|
trainable
|
If
TYPE:
|
feedback_initializer
|
Same accepted forms as
TYPE:
|
input_initializer
|
Same accepted forms as
TYPE:
|
topology
|
Same accepted forms as
TYPE:
|
seed
|
Reproducibility seed fixing the recurrent, feedback, input, bias, and orthogonal-skip draws (the skip is drawn on an independent, deterministic sub-stream). |
recurrent_initializer
|
First-class alias for
TYPE:
|
bias_initializer
|
Input/feedback initializer grammar applied to a
TYPE:
|
initial_state_initializer
|
Initializes a persistent
TYPE:
|
device
|
Initial parameter location. Metal construction initializes on CPU before transferring to support initialization operations across backends. |
dtype
|
Floating precision used during initialization, not only after conversion.
TYPE:
|
| ATTRIBUTE | DESCRIPTION |
|---|---|
state |
Current reservoir state of shape
TYPE:
|
Examples:
>>> import torch
>>> reservoir = ES2NLayer(reservoir_size=200, feedback_size=3, beta=0.1)
>>> feedback = torch.randn(4, 50, 3) # (batch, time, features)
>>> states = reservoir(feedback)
>>> states.shape
torch.Size([4, 50, 200])
See Also
resdag.layers.cells.es2n_cell.ES2NCell : Underlying single-step cell. resdag.layers.reservoirs.resesn.ResESNLayer : Decoupled-weight variant. resdag.layers.ESNLayer : Standard leaky ESN layer.
Source code in src/resdag/layers/reservoirs/es2n.py
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 | |
ResESNLayer
¶
ResESNLayer(
reservoir_size: int,
feedback_size: int,
alpha: float = 0.5,
beta: float = 0.9,
input_size: int | None = None,
spectral_radius: float | None = None,
bias: bool = True,
bias_scaling: float = 1.0,
activation: str = "tanh",
orthogonal_scaling: float = 1.0,
trainable: bool = False,
feedback_initializer: InitializerSpec = None,
input_initializer: InitializerSpec = None,
topology: TopologySpec = None,
seed: SeedLike = None,
*,
recurrent_initializer: TopologySpec = None,
bias_initializer: InitializerSpec = None,
initial_state_initializer: InitializerSpec = None,
device: device | str | None = None,
dtype: dtype | None = None
)
Bases: BaseReservoirLayer
Stateful Residual Echo State Network (ResESN) reservoir layer.
Public-facing class. Internally creates a
resdag.layers.cells.resesn_cell.ResESNCell that owns all
parameters and performs the single-step update; the sequence loop and state
management live in the parent
resdag.layers.reservoirs.base_reservoir.BaseReservoirLayer.
ResESN (Ceni & Gallicchio, 2024) generalises ES2N by decoupling the skip and nonlinear branch weights:
with independent scaling coefficients \(\alpha\) (orthogonal skip) and \(\beta\) (nonlinear branch) replacing the leak rate. \(\alpha = 1 - \beta\) recovers ES2N; \(O = I\) with \(1 - \alpha = \beta\) recovers a leaky ESN.
| PARAMETER | DESCRIPTION |
|---|---|
reservoir_size
|
Number of reservoir units (hidden-state dimension).
TYPE:
|
feedback_size
|
Dimension of the feedback signal. Required.
TYPE:
|
alpha
|
Scaling of the orthogonal skip (residual) branch. A live knob:
TYPE:
|
beta
|
Scaling of the nonlinear branch. A live knob.
TYPE:
|
input_size
|
Dimension of a driving input.
TYPE:
|
spectral_radius
|
Target spectral radius for the recurrent matrix
TYPE:
|
bias
|
Whether to include a bias term.
TYPE:
|
bias_scaling
|
Scale of the random bias (
TYPE:
|
activation
|
Activation for the nonlinear branch.
TYPE:
|
orthogonal_scaling
|
Gain on the orthogonal skip matrix
TYPE:
|
trainable
|
If
TYPE:
|
feedback_initializer
|
Same accepted forms as
TYPE:
|
input_initializer
|
Same accepted forms as
TYPE:
|
topology
|
Same accepted forms as
TYPE:
|
seed
|
Reproducibility seed fixing the recurrent, feedback, input, bias, and orthogonal-skip draws (the skip is drawn on an independent, deterministic sub-stream). |
recurrent_initializer
|
First-class alias for
TYPE:
|
bias_initializer
|
Input/feedback initializer grammar applied to a
TYPE:
|
initial_state_initializer
|
Initializes a persistent
TYPE:
|
device
|
Initial parameter location. Metal construction initializes on CPU before transferring to support initialization operations across backends. |
dtype
|
Floating precision used during initialization, not only after conversion.
TYPE:
|
| ATTRIBUTE | DESCRIPTION |
|---|---|
state |
Current reservoir state of shape
TYPE:
|
Examples:
>>> import torch
>>> reservoir = ResESNLayer(200, feedback_size=3, alpha=0.6, beta=0.4)
>>> feedback = torch.randn(4, 50, 3) # (batch, time, features)
>>> states = reservoir(feedback)
>>> states.shape
torch.Size([4, 50, 200])
See Also
resdag.layers.cells.resesn_cell.ResESNCell : Underlying single-step cell. resdag.layers.reservoirs.es2n.ES2NLayer : Convex-combination (ES2N) variant. resdag.layers.ESNLayer : Standard leaky ESN layer.
Source code in src/resdag/layers/reservoirs/resesn.py
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 | |
GatedReservoirLayer
¶
GatedReservoirLayer(
reservoir_size: int,
feedback_size: int,
input_size: int | None = None,
spectral_radius: float | None = None,
bias: bool = True,
bias_scaling: float = 1.0,
update_gate_bias: float = 2.0,
activation: str = "relu",
gate_activation: str = "sigmoid",
trainable: bool = False,
feedback_initializer: InitializerSpec = None,
input_initializer: InitializerSpec = None,
topology: TopologySpec = None,
seed: SeedLike = None,
*,
recurrent_initializer: TopologySpec = None,
bias_initializer: InitializerSpec = None,
initial_state_initializer: InitializerSpec = None,
device: device | str | None = None,
dtype: dtype | None = None,
gate_recurrent_initializer: TopologySpec = None,
gate_feedback_initializer: InitializerSpec = None,
gate_input_initializer: InitializerSpec = None,
gate_bias_initializer: InitializerSpec = None,
gate_spectral_radius: float | None = None
)
Bases: BaseReservoirLayer
Stateful RNN reservoir layer for the gated (LiGRU-style) reservoir.
Public-facing class. Internally creates a
resdag.layers.cells.gated_cell.GatedReservoirCell that owns every
weight and performs the single-step light-gated update; the sequence loop and
state management live in the parent BaseReservoirLayer, so this layer
shares the full state API (reset_state / get_state / set_state /
set_random_state), the projected fast path, and the compiled
teacher-forced scan with resdag.layers.reservoirs.esn.ESNLayer.
The state is a single packed 2-D tensor (batch, reservoir_size) (the GRU
hidden state h), following the packed multi-tensor-state convention
documented in resdag.layers.cells.gated_cell.
| PARAMETER | DESCRIPTION |
|---|---|
reservoir_size
|
Number of reservoir units (hidden state dimension).
TYPE:
|
feedback_size
|
Dimension of the feedback signal. Required.
TYPE:
|
input_size
|
Dimension of an optional driving input.
TYPE:
|
spectral_radius
|
Target spectral radius for the recurrent candidate weight. Controls
the echo of past state through the candidate path.
TYPE:
|
bias
|
Whether to include the gate biases.
TYPE:
|
bias_scaling
|
Scale of the random candidate bias
TYPE:
|
update_gate_bias
|
Constant update-gate bias biasing
TYPE:
|
activation
|
Candidate nonlinearity (LiGRU default is
TYPE:
|
gate_activation
|
Update-gate nonlinearity;
TYPE:
|
trainable
|
If
TYPE:
|
feedback_initializer
|
Initializer for the feedback drive weights. Same accepted forms as
TYPE:
|
input_initializer
|
Initializer for the driving-input drive weights. Only used when
TYPE:
|
topology
|
Structure of the recurrent candidate weight. The update-gate recurrent weight is always dense-random.
TYPE:
|
seed
|
Reproducibility seed fixing the entire reservoir. |
recurrent_initializer
|
First-class alias for
TYPE:
|
bias_initializer
|
Input/feedback initializer grammar applied to a
TYPE:
|
initial_state_initializer
|
Initializes a persistent
TYPE:
|
device
|
Initial parameter location. Metal construction initializes on CPU before transferring to support initialization operations across backends. |
dtype
|
Floating precision used during initialization, not only after conversion.
TYPE:
|
gate_recurrent_initializer
|
Separate recurrent gate matrix. Defaults to small dense random weights.
TYPE:
|
gate_spectral_radius
|
Outer radius target for the gate recurrence, respecting its scaling policy.
TYPE:
|
gate_feedback_initializer
|
Separate gate projections. Omitted projections share candidate weights.
A driver gate initializer requires
TYPE:
|
gate_input_initializer
|
Separate gate projections. Omitted projections share candidate weights.
A driver gate initializer requires
TYPE:
|
gate_bias_initializer
|
Gate-bias initializer on
TYPE:
|
| ATTRIBUTE | DESCRIPTION |
|---|---|
state |
Current packed reservoir state of shape
TYPE:
|
Examples:
Basic feedback-only gated reservoir:
>>> reservoir = GatedReservoirLayer(reservoir_size=200, feedback_size=3)
>>> feedback = torch.randn(4, 50, 3) # (batch, time, features)
>>> states = reservoir(feedback)
>>> states.shape
torch.Size([4, 50, 200])
Trainable gated reservoir (the interesting configuration):
>>> reservoir = GatedReservoirLayer(200, feedback_size=3, trainable=True)
See Also
resdag.layers.cells.gated_cell.GatedReservoirCell : Underlying single-step cell. resdag.layers.reservoirs.esn.ESNLayer : The ungated ESN layer. resdag.layers.reservoirs.base_reservoir.BaseReservoirLayer : State-management base.
Source code in src/resdag/layers/reservoirs/gated.py
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 | |
GatedReservoir
¶
Bases: GatedReservoirLayer
Deprecated alias for GatedReservoirLayer.
Retained for backward compatibility. Instantiating this class emits a
DeprecationWarning and constructs a GatedReservoirLayer;
the two are otherwise identical (GatedReservoir is a subclass, so
isinstance(GatedReservoir(...), GatedReservoirLayer) holds).
Deprecated.
Use GatedReservoirLayer instead. GatedReservoir will be
removed in a future release.
See Also
GatedReservoirLayer : The canonical class this aliases.
Source code in src/resdag/layers/reservoirs/gated.py
236 237 238 239 240 241 242 243 | |
EuSNLayer
¶
EuSNLayer(
reservoir_size: int,
feedback_size: int,
epsilon: float = 0.01,
gamma: float = 0.01,
input_size: int | None = None,
spectral_radius: float | None = None,
bias: bool = True,
bias_scaling: float = 1.0,
activation: str = "tanh",
substeps: int = 1,
solver: str = "euler",
torchdiffeq_method: str = "dopri5",
rtol: float = 1e-06,
atol: float = 1e-08,
trainable: bool = False,
feedback_initializer: InitializerSpec = None,
input_initializer: InitializerSpec = None,
topology: TopologySpec = None,
seed: SeedLike = None,
*,
recurrent_initializer: TopologySpec = None,
bias_initializer: InitializerSpec = None,
initial_state_initializer: InitializerSpec = None,
device: device | str | None = None,
dtype: dtype | None = None
)
Bases: BaseReservoirLayer
Stateful Euler State Network (EuSN) reservoir layer.
Public-facing class. Internally creates an
resdag.layers.cells.eusn_cell.EuSNCell that owns all parameters and
performs the single-step integration; the sequence loop and state management
live in the parent
resdag.layers.reservoirs.base_reservoir.BaseReservoirLayer.
EuSN (Gallicchio, arXiv:2203.09382) integrates an ODE with an antisymmetric recurrent matrix by one forward-Euler step:
The antisymmetric part \(W_r - W_r^\top\) conserves the state norm, so a small step \(\varepsilon\) gives stable, near-norm-preserving, long-memory dynamics; the diffusion \(\gamma I\) damps the Euler discretization error.
| PARAMETER | DESCRIPTION |
|---|---|
reservoir_size
|
Number of reservoir units (hidden-state dimension).
TYPE:
|
feedback_size
|
Dimension of the feedback signal. Required.
TYPE:
|
epsilon
|
Forward-Euler step size \(\varepsilon\). A live knob is not offered (the step size is baked into the integration); rebuild the layer to change it.
TYPE:
|
gamma
|
Diffusion coefficient \(\gamma \ge 0\). A live knob:
TYPE:
|
input_size
|
Dimension of a driving input.
TYPE:
|
spectral_radius
|
Target rotation rate for
TYPE:
|
bias
|
Whether to include a bias term.
TYPE:
|
bias_scaling
|
Scale of the random bias (
TYPE:
|
activation
|
Activation of the vector field (
TYPE:
|
substeps
|
Fixed integration sub-steps per interval.
TYPE:
|
solver
|
Integration scheme (see
TYPE:
|
trainable
|
If
TYPE:
|
feedback_initializer
|
Same accepted forms as
TYPE:
|
input_initializer
|
Same accepted forms as
TYPE:
|
topology
|
Same accepted forms as
TYPE:
|
seed
|
Reproducibility seed fixing the recurrent, feedback, input and bias draws. |
recurrent_initializer
|
First-class alias for
TYPE:
|
bias_initializer
|
Input/feedback initializer grammar applied to a
TYPE:
|
initial_state_initializer
|
Initializes a persistent
TYPE:
|
device
|
Initial parameter location. Metal construction initializes on CPU before transferring to support initialization operations across backends. |
dtype
|
Floating precision used during initialization, not only after conversion.
TYPE:
|
| ATTRIBUTE | DESCRIPTION |
|---|---|
state |
Current reservoir state of shape
TYPE:
|
Examples:
>>> import torch
>>> reservoir = EuSNLayer(reservoir_size=200, feedback_size=3, epsilon=0.01)
>>> feedback = torch.randn(4, 50, 3) # (batch, time, features)
>>> states = reservoir(feedback)
>>> states.shape
torch.Size([4, 50, 200])
See Also
resdag.layers.cells.eusn_cell.EuSNCell : Underlying single-step cell. resdag.layers.ESNLayer : Standard leaky-ESN layer.
Source code in src/resdag/layers/reservoirs/eusn.py
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 | |
LIFReservoirLayer
¶
LIFReservoirLayer(
reservoir_size: int,
feedback_size: int,
input_size: int | 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,
output: str = "trace",
spectral_radius: float | None = None,
bias: bool = True,
bias_scaling: float = 1.0,
trainable: bool = False,
feedback_initializer: InitializerSpec = None,
input_initializer: InitializerSpec = None,
topology: TopologySpec = None,
seed: SeedLike = None,
*,
recurrent_initializer: TopologySpec = None,
bias_initializer: InitializerSpec = None,
initial_state_initializer: InitializerSpec = None,
device: device | str | None = None,
dtype: dtype | None = None
)
Bases: BaseReservoirLayer
Stateful leaky integrate-and-fire (LIF) reservoir layer — the LSM liquid.
Public-facing class. Internally creates a
resdag.layers.cells.lif_cell.LIFCell that owns all parameters and
performs the single-step spiking update; the sequence loop and state
management live in the parent
resdag.layers.reservoirs.base_reservoir.BaseReservoirLayer, so this
layer shares the full state API (reset_state / get_state /
set_state / set_random_state) and the projected fast path with
resdag.layers.reservoirs.esn.ESNLayer.
The reservoir is a recurrent network of spiking neurons. Its per-step output
is a real-valued synaptic trace (a low-pass-filtered spike train), not the
binary spikes — so a ridge / CG readout can regress on it directly. The state
is a single packed 2-D tensor (batch, cell.state_size) bundling the
membrane potential, previous spikes, optional synaptic current, and the trace
(see resdag.layers.cells.lif_cell.LIFCell).
Important.
A Liquid State Machine is an input-driven reservoir: it maps a driving
signal to a filtered liquid state a readout regresses on. It is not a
closed-loop autoregressive chaos forecaster — the output is a spike trace,
not the feedback variable. Use resdag.models.ott_esn /
resdag.models.es2n for autoregressive chaotic forecasting.
Note.
Drive the liquid hard enough to spike: with default unit-scale weights
most neurons may never cross v_threshold, leaving the trace all-zero
and the readout with nothing to fit. Raise the input scaling and/or lower
v_threshold (check the firing rate via output="spikes"). See
resdag.models.lsm for guidance.
| PARAMETER | DESCRIPTION |
|---|---|
reservoir_size
|
Number of spiking units.
TYPE:
|
feedback_size
|
Dimension of the feedback / driving signal. Required.
TYPE:
|
input_size
|
Dimension of an optional second driving input.
TYPE:
|
tau_mem
|
Membrane time constant \(\tau_\text{mem}\).
TYPE:
|
tau_syn
|
Synaptic time constant \(\tau_\text{syn}\) (CuBa-LIF only).
TYPE:
|
dt
|
Integration timestep.
TYPE:
|
synaptic_current
|
If
TYPE:
|
v_threshold
|
Firing threshold.
TYPE:
|
reset
|
Membrane reset on a spike.
TYPE:
|
surrogate_beta
|
Fast-sigmoid surrogate slope for the straight-through spike gradient.
TYPE:
|
trace_decay
|
Decay of the low-pass readout trace.
TYPE:
|
output
|
Readable-output mode;
TYPE:
|
spectral_radius
|
Target spectral radius for the recurrent spike-coupling weight
TYPE:
|
bias
|
Whether to include a bias current.
TYPE:
|
bias_scaling
|
Scale of the random bias (
TYPE:
|
trainable
|
If
TYPE:
|
feedback_initializer
|
Same accepted forms as
TYPE:
|
input_initializer
|
Same accepted forms as
TYPE:
|
topology
|
Same accepted forms as
TYPE:
|
seed
|
Reproducibility seed fixing the recurrent, feedback, input and bias draws. |
recurrent_initializer
|
First-class alias for
TYPE:
|
bias_initializer
|
Input/feedback initializer grammar applied to a
TYPE:
|
initial_state_initializer
|
Initializes a persistent
TYPE:
|
device
|
Initial parameter location. Metal construction initializes on CPU before transferring to support initialization operations across backends. |
dtype
|
Floating precision used during initialization, not only after conversion.
TYPE:
|
| ATTRIBUTE | DESCRIPTION |
|---|---|
state |
Current packed reservoir state of shape
TYPE:
|
Examples:
>>> import torch
>>> reservoir = LIFReservoirLayer(reservoir_size=200, feedback_size=3, seed=0)
>>> feedback = torch.randn(4, 50, 3) # (batch, time, features)
>>> traces = reservoir(feedback)
>>> traces.shape
torch.Size([4, 50, 200])
See Also
resdag.layers.cells.lif_cell.LIFCell : Underlying single-step cell. resdag.layers.ESNLayer : Standard leaky-ESN layer.
Source code in src/resdag/layers/reservoirs/lif.py
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 | |
LIFReservoir
¶
Bases: LIFReservoirLayer
Deprecated alias for LIFReservoirLayer.
Retained for backward compatibility. Instantiating this class emits a
DeprecationWarning and constructs a LIFReservoirLayer;
the two are otherwise identical (LIFReservoir is a subclass, so
isinstance(LIFReservoir(...), LIFReservoirLayer) holds).
Deprecated.
Use LIFReservoirLayer instead. LIFReservoir will be
removed in a future release.
See Also
LIFReservoirLayer : The canonical class this aliases.
Source code in src/resdag/layers/reservoirs/lif.py
246 247 248 249 250 251 252 253 | |
CoRNNLayer
¶
CoRNNLayer(
reservoir_size: int,
feedback_size: int,
input_size: int | None = None,
*,
dt: float = 0.1,
gamma: float = 1.0,
epsilon: float = 1.0,
recurrent_initializer: RecurrentInitializerSpec = None,
velocity_initializer: RecurrentInitializerSpec = None,
topology: TopologySpec = None,
spectral_radius: float | None = None,
feedback_initializer: InitializerSpec = None,
input_initializer: InitializerSpec = None,
bias: bool = True,
bias_scaling: float = 1.0,
trainable: bool = False,
seed: SeedLike = None,
device: device | str | None = None,
dtype: dtype | None = None
)
Bases: CellReservoirLayer
Stateful coRNN layer; see CoRNNCell for dynamics and packed states.
forward returns position sequences, forward_stateless additionally
returns packed position/velocity state. The shared reservoir layer supports
chunked state, differentiable scans, and projected inference/forecasting.
Source code in src/resdag/layers/reservoirs/cornn.py
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 | |
LegendreDelayLayer
¶
LegendreDelayLayer(
order: int,
feedback_size: int,
input_size: int | None = None,
*,
theta: float = 100.0,
dt: float = 1.0,
memory_channels: int | None = None,
feedback_initializer: InitializerSpec = None,
input_initializer: InitializerSpec = None,
trainable: bool = False,
seed: SeedLike = None,
device: device | str | None = None,
dtype: dtype | None = None
)
Bases: CellReservoirLayer
Stateful fixed LDN memory; see LegendreDelayCell for configuration.
Returns order * memory_channels coefficients per timestep, flattened
channel first. Default channels preserve all feedback and driver dimensions.
theta and dt use the same time units and fix the discretization at
construction. This is linear delay memory, not a full nonlinear LMU.
Source code in src/resdag/layers/reservoirs/legendre_delay.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 | |
TorchRecurrentLayer
¶
TorchRecurrentLayer(
cell: GRUCell | LSTMCell,
feedback_size: int,
input_size: int | None = None,
*,
trainable: bool = False
)
Bases: CellReservoirLayer
Wrap a copy of a standard GRUCell/LSTMCell, frozen by default.
Inherits device/dtype and parameter values from cell. See
TorchRecurrentCell for feedback/driver ordering and packed LSTM
state. Sequence output contains only hidden states, not LSTM carry states.
Set trainable=True to include this layer in a larger gradient pipeline.
Source code in src/resdag/layers/reservoirs/torch_recurrent.py
19 20 21 22 23 24 25 26 27 | |
Readouts¶
Use fit for algebraic training and ordinary module calls for predictions.
Custom solvers implement ReadoutLayer.solve(states, targets), returning
coefficients in (input_features, output_features) order and an optional
intercept. The base class handles shapes, validation and parameter copy-back.
solve can update diagnostics or online statistics; it is a fitting hook.
Incremental ridge uses partial_fit then finalize; RLS supports partial_fit
and resetting fit_online. Both expose n_seen as a progress diagnostic.
Their persistent statistics keep stable checkpoint keys. See
custom solvers.
The opt-in LSMR readout and its solve reports have a dedicated API reference and memory/device guide.
readouts
¶
Readout Layers¶
This module provides readout layer implementations for ESN models.
| CLASS | DESCRIPTION |
|---|---|
ReadoutLayer |
Base per-timestep linear layer with fitting interface. |
AutoReadoutLayer |
Precision-aware automatic L2 fitting with explicit solver overrides. |
CGReadoutLayer |
Readout with Conjugate Gradient ridge regression solver. |
LSMRReadoutLayer |
Opt-in CPU float64 matrix-free ridge fit with SciPy LSMR. |
RidgeReadoutLayer |
Direct ridge readout via Cholesky ( |
CholeskyReadoutLayer |
Single-shot Cholesky ridge readout; the streaming-path direct solver. |
SVDReadoutLayer |
Readout solved via SVD with Tikhonov filter factors; robust to
rank-deficient Gram matrices and |
PinvReadoutLayer |
Least-squares readout via |
IncrementalRidgeReadoutLayer |
Streaming ridge readout: |
RLSReadout |
True-online Recursive Least Squares readout with a forgetting factor:
|
FISTAReadoutLayer |
Sparse / robust readout: L1 (lasso) or elastic-net regression solved with FISTA (accelerated proximal gradient), batched over all outputs. |
The old names `IncrementalRidgeReadout` and `FISTAReadout` are retained as |
|
deprecated aliases of `IncrementalRidgeReadoutLayer` / `FISTAReadoutLayer`. |
|
Examples:
>>> from resdag.layers.readouts import CGReadoutLayer
>>> readout = CGReadoutLayer(
... in_features=200,
... out_features=3,
... alpha=1e-6,
... name="output",
... )
>>> # Fit using ESNTrainer or directly
>>> readout.fit(states, targets)
>>> output = readout(states)
See Also
resdag.training.ESNTrainer : Trainer that uses these readouts. resdag.layers.ESNLayer : ESN layer for generating states.
ReadoutLayer
¶
ReadoutLayer(
in_features: int,
out_features: int,
bias: bool = True,
name: str | None = None,
trainable: bool = False,
)
Bases: Linear
Per-timestep linear layer with custom fitting for ESN training.
This layer extends torch.nn.Linear with:
- Per-timestep application to sequence tensors
(B, T, F) - Named identification for multi-readout architectures
- Custom
fit()interface for classical ESN training
The layer applies the same linear transformation independently to each timestep in a sequence:
Input: (B, T, F_in) -> Reshape to (B*T, F_in)
Apply: linear(x) = x @ W.T + b
Output: (B*T, F_out) -> Reshape to (B, T, F_out)
This matches classical ESN semantics where readouts are fitted across the entire sequence at once using ridge regression.
| PARAMETER | DESCRIPTION |
|---|---|
in_features
|
Size of input features.
TYPE:
|
out_features
|
Size of output features.
TYPE:
|
bias
|
Whether to include a bias term.
TYPE:
|
name
|
Name for this readout layer. Used for identification in
multi-readout architectures and by
TYPE:
|
trainable
|
If True, weights are trainable via backpropagation. If False, weights are frozen (standard ESN behavior).
TYPE:
|
| ATTRIBUTE | DESCRIPTION |
|---|---|
weight |
Weight matrix of shape
TYPE:
|
bias |
Bias vector of shape
TYPE:
|
name |
Name of this readout layer.
TYPE:
|
is_fitted |
True if
TYPE:
|
Examples:
Basic usage:
>>> readout = ReadoutLayer(in_features=100, out_features=10)
>>> x = torch.randn(2, 20, 100) # (batch, seq_len, features)
>>> y = readout(x)
>>> print(y.shape)
torch.Size([2, 20, 10])
Named readout for multi-output architectures:
>>> readout1 = ReadoutLayer(100, 10, name="position")
>>> readout2 = ReadoutLayer(100, 3, name="velocity")
See Also
CGReadoutLayer : Readout with Conjugate Gradient solver. resdag.training.ESNTrainer : Trainer for fitting readouts.
Source code in src/resdag/layers/readouts/base.py
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 | |
trainable
property
writable
¶
trainable: bool
bool : Whether the readout weights participate in backpropagation.
A live switch: assigning to it flips requires_grad_ on every
readout parameter (weight and, when present, bias). A
post-construction readout.trainable = True therefore genuinely
unfreezes the readout for a gradient-based rollout rather than silently
shadowing a construction-time-only flag. The getter reflects the
current state.
is_fitted
property
¶
is_fitted: bool
bool : True if fit() has been called successfully.
Backed by a registered buffer (so the flag is preserved across
state_dict / load_state_dict round-trips) but read from a plain
Python mirror kept coherent with it. Reading the mirror avoids the
buffer .item() device->host sync — negligible once, but ruinous
inside a per-step autoregressive forecast loop and a torch.compile
graph-break.
forward
¶
Apply linear transformation to input.
Handles both 2D (batch, features) and 3D (batch, seq_len, features)
inputs. For 3D inputs, applies the linear transformation independently
to each timestep.
| PARAMETER | DESCRIPTION |
|---|---|
input
|
Input tensor of shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Output tensor of shape |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If input has neither 2 nor 3 dimensions. |
Examples:
>>> readout = ReadoutLayer(100, 10)
>>> x_2d = torch.randn(4, 100)
>>> y_2d = readout(x_2d) # (4, 10)
>>> x_3d = torch.randn(4, 50, 100)
>>> y_3d = readout(x_3d) # (4, 50, 10)
Source code in src/resdag/layers/readouts/base.py
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 | |
fit
¶
Fit readout weights to the given (states, targets) pair.
This base implementation handles the bookkeeping that every readout
needs: shape normalisation from (B, T, F) → (B*T, F) plus
sample-count and out-features validation. The actual algebraic
solve is delegated to solve, which subclasses override.
| PARAMETER | DESCRIPTION |
|---|---|
states
|
Input states of shape
TYPE:
|
targets
|
Target outputs of shape
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
NotImplementedError
|
The base |
ValueError
|
If |
Notes
After fit() returns successfully, is_fitted is True.
See Also
CGReadoutLayer : Concrete implementation using Conjugate Gradient.
Source code in src/resdag/layers/readouts/base.py
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 | |
solve
¶
Solve the readout fit on already-flattened inputs.
Subclasses override this hook instead of fit so they don't
need to re-implement shape normalisation, validation, or parameter
copy-back.
This is a fitting extension hook, not a pure analysis operation.
Online variants may update accumulated/recursive statistics and
installed coefficients. Use fit as the training entrypoint.
| PARAMETER | DESCRIPTION |
|---|---|
states
|
Flattened input states of shape
TYPE:
|
targets
|
Flattened targets of shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
coefs
|
Coefficient matrix of shape
TYPE:
|
intercept
|
Bias vector of shape
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
NotImplementedError
|
The base class does not implement an algebraic solve. |
Source code in src/resdag/layers/readouts/base.py
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 | |
AutoReadoutLayer
¶
AutoReadoutLayer(
in_features: int,
out_features: int,
bias: bool = True,
name: str | None = None,
trainable: bool = False,
alpha: float = 1e-06,
solver: Solver = "auto",
solve_dtype: dtype | None = None,
rcond: float | None = None,
cpu_fallback: bool = True,
)
Bases: ReadoutLayer
Fit the same L2 readout with an automatic or explicitly chosen solver.
Every method minimizes ||X W + b - Y||² + alpha ||W||². The intercept
is unpenalized. Automatic recovery never increases alpha and never
switches to an L1 or online-learning objective.
Automatic fitting first tries a smaller primal (features by features) or
dual (samples by samples) Cholesky system. It accepts that route only
when a full inverse-norm conditioning estimate, a conservative bound for
Gram formation roundoff and a scale-relative residual pass their checks.
Rejected tall systems use augmented QR, then SVD if rank/conditioning
makes triangular substitution unreliable. Wide least-squares problems
use SVD for their minimum-norm solution. These are numerical guards, not
accuracy guarantees; inspect last_solve to see the selected path.
| PARAMETER | DESCRIPTION |
|---|---|
in_features
|
Input and output dimensions, as for
TYPE:
|
out_features
|
Input and output dimensions, as for
TYPE:
|
bias
|
Fit an unpenalized intercept by centering the training data.
TYPE:
|
name
|
Readout name used by custom graphs and training targets.
TYPE:
|
trainable
|
Allow ordinary PyTorch gradients through the fitted linear layer. Algebraic fitting itself does not build a differentiation graph.
TYPE:
|
alpha
|
Finite nonnegative L2 penalty. The requested value is never inflated.
TYPE:
|
solver
|
Force an algorithm or let the layer choose. A forced algorithm is never replaced by another. Unsafe forced normal equations warn; unrepresentable products, failed factorization or unreliable forced QR raises an error.
TYPE:
|
solve_dtype
|
Working precision:
TYPE:
|
rcond
|
Finite nonnegative relative singular-value cutoff for unregularized SVD and QR rank checks. Default: working epsilon times max(N, F). Positive-ridge SVD uses every singular value and the exact penalty.
TYPE:
|
cpu_fallback
|
Allow an explicit CPU float64 bridge when MPS needs a stable
decomposition, or another accelerator lacks a required operation.
Each bridge warns and is recorded in
TYPE:
|
Examples:
>>> readout = AutoReadoutLayer(100, 3, alpha=1e-6)
>>> readout.fit(torch.randn(200, 100), torch.randn(200, 3))
>>> readout.last_solve.solver in ("primal", "qr", "svd")
True
Source code in src/resdag/layers/readouts/auto_readout.py
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 | |
solve
¶
Solve flattened training data and record the actual numerical path.
Source code in src/resdag/layers/readouts/auto_readout.py
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 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 | |
ReadoutSolveReport
dataclass
¶
ReadoutSolveReport(
requested_solver: str,
solver: str,
alpha: float,
input_device: str,
input_dtype: dtype,
solve_device: str,
solve_dtype: dtype,
n_samples: int,
n_features: int,
condition_estimate: float,
roundoff_estimate: float | None,
relative_optimality_residual: float,
relative_prediction_residual: float,
fallback_reasons: tuple[str, ...],
precision_warning: str | None,
)
Diagnostics for the last successful algebraic solve.
Residuals describe the working-precision solution before its cast back to
the input/parameter dtype. relative_optimality_residual measures the
ridge first-order equations; relative_prediction_residual measures
training prediction error, which need not be small for a regularized fit.
Conditioning and roundoff quantities are conservative numerical estimates,
not guarantees about forecast accuracy. This report is ordinary Python
metadata; it adds no objects to a PyTorch state_dict.
CGReadoutLayer
¶
CGReadoutLayer(
in_features: int,
out_features: int,
bias: bool = True,
name: str | None = None,
trainable: bool = False,
max_iter: int = 100,
tol: float = 1e-05,
alpha: float = 1e-06,
use_float64: bool = True,
gram_dtype: dtype | None = None,
)
Bases: ReadoutLayer
Readout layer with Conjugate Gradient ridge regression solver.
This layer extends ReadoutLayer with an efficient Conjugate
Gradient (CG) solver for fitting weights via ridge regression. The CG
solver is:
- Forms the feature-by-feature Gram matrix, then iterates on that system
- Uses Torch operations on the input device
- Configurable working precision; normal equations can still lose accuracy
- Supports batched time-series data
The solver finds weights W that minimize:
where \(\alpha\) is the regularization strength.
| PARAMETER | DESCRIPTION |
|---|---|
in_features
|
Size of input features (reservoir state dimension).
TYPE:
|
out_features
|
Size of output features (prediction dimension).
TYPE:
|
bias
|
Whether to include a bias term.
TYPE:
|
name
|
Name for this readout layer. Used for identification in
multi-readout architectures and by
TYPE:
|
trainable
|
If True, weights are trainable via backpropagation.
TYPE:
|
alpha
|
L2 regularization strength. Must be non-negative. Larger values provide more regularization (smoother outputs, less overfitting).
TYPE:
|
max_iter
|
Maximum number of CG iterations. Must be a positive integer.
TYPE:
|
tol
|
Convergence tolerance for the CG solver. Must be positive. Each output
column is considered converged when its residual-norm-squared falls
below
TYPE:
|
use_float64
|
If
TYPE:
|
gram_dtype
|
Dtype for forming the Gram matrix and right-hand side (the heavy
TYPE:
|
| ATTRIBUTE | DESCRIPTION |
|---|---|
weight |
Weight matrix of shape
TYPE:
|
bias |
Bias vector of shape
TYPE:
|
alpha |
L2 regularization strength.
TYPE:
|
max_iter |
Maximum CG iterations.
TYPE:
|
tol |
Convergence tolerance.
TYPE:
|
Examples:
Basic usage:
>>> readout = CGReadoutLayer(in_features=100, out_features=10, alpha=1e-6)
>>> states = torch.randn(32, 50, 100) # (batch, time, features)
>>> targets = torch.randn(32, 50, 10)
>>> readout.fit(states, targets)
>>> output = readout(states)
>>> print(output.shape)
torch.Size([32, 50, 10])
With custom regularization:
>>> readout = CGReadoutLayer(100, 10, alpha=1e-4) # Stronger regularization
>>> readout.fit(states, targets)
See Also
ReadoutLayer : Base readout layer class. resdag.training.ESNTrainer : Trainer that uses this for fitting.
Source code in src/resdag/layers/readouts/cg_readout.py
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 | |
solve
¶
Solve ridge regression via Conjugate Gradient on flattened inputs.
| PARAMETER | DESCRIPTION |
|---|---|
states
|
Flattened state matrix of shape
TYPE:
|
targets
|
Flattened target matrix of shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
coefs
|
Coefficient matrix of shape
TYPE:
|
intercept
|
Intercept vector of shape
TYPE:
|
Source code in src/resdag/layers/readouts/cg_readout.py
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 | |
RidgeReadoutLayer
¶
RidgeReadoutLayer(
in_features: int,
out_features: int,
bias: bool = True,
name: str | None = None,
trainable: bool = False,
alpha: float = 1e-06,
solver: str = "cholesky",
state_noise: float = 0.0,
noise_draws: int | None = None,
noise_seed: int | None = None,
use_float64: bool = True,
gram_dtype: dtype | None = None,
)
Bases: ReadoutLayer
Readout layer with a direct ridge-regression solver.
For the readout widths typical of reservoir computing
(in_features = 100–2000) the (F, F) Gram matrix factorises
exactly and almost instantly. A direct Cholesky solve is both faster and
exact (up to floating point), whereas CGReadoutLayer only
approximates the solution and can under-converge on the ill-conditioned
concatenated-input readouts produced by ott_esn / power_augmented.
The solver minimises the same ridge objective as CGReadoutLayer,
by forming the regularised normal equations (XᵀX + αI) W = Xᵀy and
solving them with one of:
solver='cholesky'(default) —torch.linalg.choleskyfollowed bytorch.linalg.cholesky_solve. Exploits the symmetric positive definiteness ofXᵀX + αIin exact arithmetic foralpha > 0. Finite-precision Gram formation can still lose positive definiteness.solver='solve'—torch.linalg.solve(LU). It does not require positive definiteness, so it supportsalpha == 0on a full-rank Gram.
Solver-selection guide
- Default to
RidgeReadoutLayer(solver='cholesky')for any well-conditioned readout withalpha > 0when an explicit normal-equations solve is desired. Runtime and accuracy depend on the workload, precision and hardware.AutoReadoutLayerchecks numerical safety and can use the original design matrix instead. - Use
solver='solve'when you needalpha == 0(pure least squares) and the Gram is full rank but you don't want the SVD machinery. - If the Gram is rank deficient (high-degree NG-RC feature maps, more
features than samples), a Cholesky/LU solve will fail or be unstable —
reach for
SVDReadoutLayer(filter factors) orPinvReadoutLayer(lstsq / pinv) instead.
Noise-injection / LMNT regularization
Pass state_noise > 0 to apply state-noise regularization, a standard,
tunable tool for closed-loop (autonomous-rollout) robustness rather than
only weight magnitude. Fitting on state-noise-perturbed reservoir states
mimics the feedback error the model sees when it free-runs on its own output
— the injected noise trades a little one-step accuracy for closed-loop
stability (Jaeger's state-noise idea; Wikner et al. 2024, Stabilizing
machine learning prediction of dynamics, Chaos 34, 043105). It is not a
free or automatic forecast-quality win: whether the trade nets out positive
is problem- and \(\sigma\)-dependent — it can help or hurt, and
\(\sigma\) must be tuned per problem. The shipped default is 0.0
(off); opt in and tune.
The robust guarantee is the mechanism, not a VPT number: by default
(noise_draws=None) the closed-form LMNT (Linearized Multi-Noise
Training) path computes the exact analytic expectation of the
noise-perturbed Gram — a single scalar on the diagonal (\(N\sigma^2\)
raw, \((N-1)\sigma^2\) centered). One solve of the expected normal
equations is the infinite-draw limit of the explicit-noise path. This is
not the expectation of separately fitted coefficients or chaotic forecasts.
Set noise_draws=M to average the normal equations of M explicit
Gaussian-perturbed copies before solving once (seeded by noise_seed).
This Monte-Carlo path converges to the analytic path as M grows. state_noise is
independent of alpha: they add on the diagonal
(\(\alpha + N\sigma^2\)) but noise training targets rollout robustness
while alpha targets weight norm.
| PARAMETER | DESCRIPTION |
|---|---|
in_features
|
Size of input features (reservoir state dimension).
TYPE:
|
out_features
|
Size of output features (prediction dimension).
TYPE:
|
bias
|
Whether to include a bias term. When
TYPE:
|
name
|
Name for this readout layer. Used for identification in multi-readout
architectures and as the key into
TYPE:
|
trainable
|
If
TYPE:
|
alpha
|
L2 regularization strength. Must be non-negative.
TYPE:
|
solver
|
Direct solver to use for the normal equations.
TYPE:
|
state_noise
|
Standard deviation \(\sigma\) of the Gaussian state noise the readout
is regularised against for closed-loop stability (see the class
docstring).
TYPE:
|
noise_draws
|
When
TYPE:
|
noise_seed
|
Seed for the explicit-noise (
TYPE:
|
use_float64
|
If
TYPE:
|
gram_dtype
|
Dtype for forming the Gram matrix and right-hand side (the heavy
TYPE:
|
| ATTRIBUTE | DESCRIPTION |
|---|---|
weight |
Weight matrix of shape
TYPE:
|
bias |
Bias vector of shape
TYPE:
|
alpha |
L2 regularization strength.
TYPE:
|
solver |
The selected direct solver.
TYPE:
|
state_noise |
Standard deviation of the closed-loop state-noise regulariser.
TYPE:
|
Examples:
>>> readout = RidgeReadoutLayer(in_features=200, out_features=3, alpha=1e-6)
>>> states = torch.randn(8, 50, 200) # (batch, time, features)
>>> targets = torch.randn(8, 50, 3)
>>> readout.fit(states, targets)
>>> output = readout(states)
>>> output.shape
torch.Size([8, 50, 3])
Closed-form LMNT noise regularisation for closed-loop robustness (the
state_noise value below is illustrative — tune it per problem, and
expect it to help or hurt depending on the system and \(\sigma\)):
>>> readout = RidgeReadoutLayer(200, 3, alpha=1e-8, state_noise=1e-3)
See Also
CGReadoutLayer : Iterative Conjugate Gradient ridge readout. SVDReadoutLayer : SVD filter-factor readout for rank-deficient Gram. PinvReadoutLayer : lstsq / pseudo-inverse readout. resdag.training.ESNTrainer : Trainer that uses this for fitting.
Source code in src/resdag/layers/readouts/ridge_readout.py
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 | |
solve
¶
Solve ridge regression directly on flattened inputs.
| PARAMETER | DESCRIPTION |
|---|---|
states
|
Flattened state matrix of shape
TYPE:
|
targets
|
Flattened target matrix of shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
coefs
|
Coefficient matrix of shape
TYPE:
|
intercept
|
Intercept vector of shape
TYPE:
|
Source code in src/resdag/layers/readouts/ridge_readout.py
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 | |
CholeskyReadoutLayer
¶
CholeskyReadoutLayer(
in_features: int,
out_features: int,
bias: bool = True,
name: str | None = None,
trainable: bool = False,
alpha: float = 1e-06,
state_noise: float = 0.0,
noise_draws: int | None = None,
noise_seed: int | None = None,
use_float64: bool = True,
gram_dtype: dtype | None = None,
)
Bases: ReadoutLayer
Readout layer that solves ridge regression via a Cholesky factorisation.
The regularised normal equations (XᵀX + αI) W = Xᵀy are formed (with
analytic centering when a bias is fitted) and solved with
torch.linalg.cholesky followed by torch.cholesky_solve. The
(F, F) system is symmetric positive definite for alpha > 0, so the
Cholesky factorisation is the fastest, most numerically stable exact solve
for the readout widths typical of reservoir computing
(in_features = 100–2000).
Unlike CGReadoutLayer, which only approximates the solution
iteratively, this layer returns the exact ridge solution (up to floating
point) in a single shot. It is the single-batch counterpart of the
streaming IncrementalRidgeReadoutLayer: both ultimately Cholesky-solve
the same regularised Gram system, so a full-batch CholeskyReadoutLayer
fit and an accumulated IncrementalRidgeReadoutLayer fit over the same data
agree to within floating-point tolerance.
The solver minimises the same ridge objective as CGReadoutLayer,
Noise-injection / LMNT regularization
Pass state_noise > 0 to apply state-noise regularization — a
standard, tunable tool for closed-loop (autonomous-rollout) robustness —
by training on state-noise-perturbed reservoir states (Jaeger's state noise;
Wikner et al. 2024, Chaos 34, 043105). It trades a little one-step accuracy
for closed-loop stability; it is not an automatic forecast-quality win
(whether it helps or hurts is problem- and \(\sigma\)-dependent, so
\(\sigma\) must be tuned per problem — the default is off). The robust
guarantee is the mechanism: the default noise_draws=None uses the
closed-form LMNT term — the exact analytic expectation of the noisy
Gram. Solving these expected normal equations is the infinite-copy limit of
explicit-noise training; it does not average separately fitted coefficients.
Set noise_draws=M (seeded by noise_seed) to average the normal
equations of M noisy copies, then solve once. See RidgeReadoutLayer for the
full discussion. 0.0 (default) is byte-identical to a plain fit.
| PARAMETER | DESCRIPTION |
|---|---|
in_features
|
Size of input features (reservoir state dimension).
TYPE:
|
out_features
|
Size of output features (prediction dimension).
TYPE:
|
bias
|
Whether to include a bias term. When
TYPE:
|
name
|
Name for this readout layer. Used for identification in multi-readout
architectures and as the key into
TYPE:
|
trainable
|
If
TYPE:
|
alpha
|
L2 regularization strength. Must be non-negative.
TYPE:
|
state_noise
|
Standard deviation \(\sigma\) of the closed-loop state-noise
regulariser (see the class docstring).
TYPE:
|
noise_draws
|
TYPE:
|
noise_seed
|
Seed for the explicit-noise (
TYPE:
|
use_float64
|
If
TYPE:
|
gram_dtype
|
Dtype for forming the Gram matrix and right-hand side (the heavy
TYPE:
|
| ATTRIBUTE | DESCRIPTION |
|---|---|
weight |
Weight matrix of shape
TYPE:
|
bias |
Bias vector of shape
TYPE:
|
alpha |
L2 regularization strength.
TYPE:
|
Examples:
>>> readout = CholeskyReadoutLayer(in_features=200, out_features=3, alpha=1e-6)
>>> states = torch.randn(8, 50, 200) # (batch, time, features)
>>> targets = torch.randn(8, 50, 3)
>>> readout.fit(states, targets)
>>> output = readout(states)
>>> output.shape
torch.Size([8, 50, 3])
See Also
CGReadoutLayer : Iterative Conjugate Gradient ridge readout.
RidgeReadoutLayer : Direct ridge readout with a solver switch.
IncrementalRidgeReadoutLayer : Streaming partial_fit / finalize counterpart.
resdag.training.ESNTrainer : Trainer that uses this for fitting.
Source code in src/resdag/layers/readouts/cholesky_readout.py
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 | |
solve
¶
Solve ridge regression via a Cholesky factorisation on flattened inputs.
| PARAMETER | DESCRIPTION |
|---|---|
states
|
Flattened state matrix of shape
TYPE:
|
targets
|
Flattened target matrix of shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
coefs
|
Coefficient matrix of shape
TYPE:
|
intercept
|
Intercept vector of shape
TYPE:
|
Source code in src/resdag/layers/readouts/cholesky_readout.py
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 | |
SVDReadoutLayer
¶
SVDReadoutLayer(
in_features: int,
out_features: int,
bias: bool = True,
name: str | None = None,
trainable: bool = False,
alpha: float = 0.0,
rcond: float = 1e-15,
use_float64: bool = True,
gram_dtype: dtype | None = None,
)
Bases: ReadoutLayer
Readout layer solved via SVD with Tikhonov filter factors.
The (optionally centered) design matrix X is decomposed as
X = U diag(s) Vᵀ and the ridge solution is reconstructed with
filter factors
For alpha > 0 this is exactly the ridge solution; for alpha == 0 it
collapses to the minimum-norm least-squares solution, with singular values
at or below an rcond cutoff dropped so a rank-deficient Gram (more
features than independent samples, or the near-collinear columns produced
by high-degree NG-RC feature maps) is handled gracefully instead of
blowing up the way a Cholesky / normal-equations solve would.
Positive-ridge filter factors are evaluated in scaled form, avoiding
overflow from squaring large finite singular values. The requested
alpha is preserved; numerical recovery does not add extra regularization.
Decomposing X directly avoids squaring its condition number by forming
XᵀX. This is useful for rank-deficient or ill-conditioned features;
attainable accuracy still depends on working precision, data scale and
regularization.
Solver-selection guide
- Reach for
SVDReadoutLayerwhen the Gram is rank deficient or severely ill-conditioned:alpha == 0least squares, high-degree NG-RC feature maps, or wide concatenated-input readouts where CG under-converges. - Cholesky-based
RidgeReadoutLayercan reduce fitting cost when the regularized Gram is well conditioned. Measure accuracy and runtime for the actual matrix shape, dtype and device when choosing a solver. PinvReadoutLayeris the closely-related lstsq / pinv route; SVD here gives explicit control over the Tikhonov filter andrcond.
| PARAMETER | DESCRIPTION |
|---|---|
in_features
|
Size of input features (reservoir state dimension).
TYPE:
|
out_features
|
Size of output features (prediction dimension).
TYPE:
|
bias
|
Whether to include a bias term. When
TYPE:
|
name
|
Name for this readout layer. Used for identification in multi-readout
architectures and as the key into
TYPE:
|
trainable
|
If
TYPE:
|
alpha
|
Tikhonov (L2) regularization strength. Must be finite and non-negative.
TYPE:
|
rcond
|
Finite, non-negative relative cutoff for small singular values. Values at or below
TYPE:
|
use_float64
|
If
TYPE:
|
gram_dtype
|
Dtype for forming / casting the design matrix. Default
TYPE:
|
| ATTRIBUTE | DESCRIPTION |
|---|---|
weight |
Weight matrix of shape
TYPE:
|
bias |
Bias vector of shape
TYPE:
|
alpha |
Tikhonov regularization strength.
TYPE:
|
rcond |
Relative singular-value cutoff.
TYPE:
|
Examples:
>>> readout = SVDReadoutLayer(in_features=200, out_features=3, alpha=0.0)
>>> states = torch.randn(8, 50, 200) # (batch, time, features)
>>> targets = torch.randn(8, 50, 3)
>>> readout.fit(states, targets)
>>> output = readout(states)
>>> output.shape
torch.Size([8, 50, 3])
See Also
RidgeReadoutLayer : Cholesky / solve direct readout (faster, full rank). PinvReadoutLayer : lstsq / pseudo-inverse readout. CGReadoutLayer : Iterative Conjugate Gradient ridge readout. resdag.training.ESNTrainer : Trainer that uses this for fitting.
Source code in src/resdag/layers/readouts/svd_readout.py
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 | |
solve
¶
Solve the readout via SVD filter factors on flattened inputs.
| PARAMETER | DESCRIPTION |
|---|---|
states
|
Flattened state matrix of shape
TYPE:
|
targets
|
Flattened target matrix of shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
coefs
|
Coefficient matrix of shape
TYPE:
|
intercept
|
Intercept vector of shape
TYPE:
|
Source code in src/resdag/layers/readouts/svd_readout.py
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 | |
PinvReadoutLayer
¶
PinvReadoutLayer(
in_features: int,
out_features: int,
bias: bool = True,
name: str | None = None,
trainable: bool = False,
rcond: float = 1e-15,
solver: str = "lstsq",
use_float64: bool = True,
gram_dtype: dtype | None = None,
)
Bases: ReadoutLayer
Readout layer solved via least squares / pseudo-inverse.
Solves the (optionally centered) least-squares problem
min_W ||X W - Y|| directly, without forming the Gram matrix, using one
of:
solver='lstsq'(default) —torch.linalg.lstsqwith thegelsddriver, a divide-and-conquer SVD-based least-squares solver that returns the minimum-norm solution for rank-deficientXand honours thercondcutoff.solver='pinv'— form the Moore–Penrose pseudo-inversetorch.linalg.pinv(X, rcond=...)and apply it toY. Equivalent in result but materialises the(F, N)pseudo-inverse explicitly.
This is a pure least-squares readout: there is no Tikhonov penalty
(alpha). Regularisation comes only from the rcond truncation of
small singular values. If you need an explicit ridge penalty use
RidgeReadoutLayer or SVDReadoutLayer (which exposes both
alpha and rcond).
Solver-selection guide
- Reach for
PinvReadoutLayerfor unregularised least squares on a possibly rank-deficient design matrix when you want the minimum-norm solution and don't need a Tikhonovalpha. solver='lstsq'(default) is the right choice almost always — it never materialises the pseudo-inverse. Usesolver='pinv'only if you specifically want the pseudo-inverse matrix itself.- For an explicit ridge penalty, prefer
SVDReadoutLayer(filter factors,alpha+rcond) orRidgeReadoutLayer(Cholesky, fast, full rank).
| PARAMETER | DESCRIPTION |
|---|---|
in_features
|
Size of input features (reservoir state dimension).
TYPE:
|
out_features
|
Size of output features (prediction dimension).
TYPE:
|
bias
|
Whether to include a bias term. When
TYPE:
|
name
|
Name for this readout layer. Used for identification in multi-readout
architectures and as the key into
TYPE:
|
trainable
|
If
TYPE:
|
rcond
|
Relative cutoff for small singular values. Singular values at or below
TYPE:
|
solver
|
Whether to solve with
TYPE:
|
use_float64
|
If
TYPE:
|
gram_dtype
|
Dtype for forming / casting the design matrix. Default
TYPE:
|
| ATTRIBUTE | DESCRIPTION |
|---|---|
weight |
Weight matrix of shape
TYPE:
|
bias |
Bias vector of shape
TYPE:
|
rcond |
Relative singular-value cutoff.
TYPE:
|
solver |
The selected least-squares solver.
TYPE:
|
Examples:
>>> readout = PinvReadoutLayer(in_features=200, out_features=3)
>>> states = torch.randn(8, 50, 200) # (batch, time, features)
>>> targets = torch.randn(8, 50, 3)
>>> readout.fit(states, targets)
>>> output = readout(states)
>>> output.shape
torch.Size([8, 50, 3])
See Also
SVDReadoutLayer : SVD filter-factor readout with explicit alpha.
RidgeReadoutLayer : Cholesky / solve direct ridge readout.
CGReadoutLayer : Iterative Conjugate Gradient ridge readout.
resdag.training.ESNTrainer : Trainer that uses this for fitting.
Source code in src/resdag/layers/readouts/pinv_readout.py
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 | |
solve
¶
Solve the readout via least squares / pinv on flattened inputs.
| PARAMETER | DESCRIPTION |
|---|---|
states
|
Flattened state matrix of shape
TYPE:
|
targets
|
Flattened target matrix of shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
coefs
|
Coefficient matrix of shape
TYPE:
|
intercept
|
Intercept vector of shape
TYPE:
|
Source code in src/resdag/layers/readouts/pinv_readout.py
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 | |
IncrementalRidgeReadoutLayer
¶
IncrementalRidgeReadoutLayer(
in_features: int,
out_features: int,
bias: bool = True,
name: str | None = None,
trainable: bool = False,
alpha: float = 1e-06,
use_float64: bool = True,
gram_dtype: dtype | None = None,
)
Bases: ReadoutLayer
Readout layer that fits ridge regression incrementally over chunks.
The classic readout fit requires every state in memory at once. This layer instead accumulates the ridge sufficient statistics as chunks arrive:
XtX/Xty— centered cross-products whenbias=Trueand raw products whenbias=False,_mean_x/_mean_y— stable running means for the intercept,sum_x/sum_y— retained column sums,n— the running sample count.
Centered chunk statistics are merged using the Chan covariance formula, so
accumulating them chunk-by-chunk and solving once is algebraically identical
to forming the whole Gram in a
single pass. finalize assembles the centered, regularised normal
equations from the running statistics and Cholesky-solves them, recovering
the same coefficients (within floating point) that a full-batch
CholeskyReadoutLayer / CGReadoutLayer fit would produce.
The ridge objective is identical to the single-shot readouts,
with the intercept (when bias=True) recovered from the running means and
left un-penalised, exactly as in the shared _solve_utils centering.
Lifecycle
- (Optionally)
reset_accumulatorsto clear any prior statistics. - Call
partial_fitonce per chunk to accumulate statistics. - Call
finalizeonce to solve and write the fitted weights.
is_fitted becomes True only after finalize; calling
forward before that raises a clear RuntimeError.
| PARAMETER | DESCRIPTION |
|---|---|
in_features
|
Size of input features (reservoir state dimension).
TYPE:
|
out_features
|
Size of output features (prediction dimension).
TYPE:
|
bias
|
Whether to include a bias term. When
TYPE:
|
name
|
Name for this readout layer. Used for identification in multi-readout
architectures and as the key into
TYPE:
|
trainable
|
If
TYPE:
|
alpha
|
L2 regularization strength. Must be non-negative.
TYPE:
|
use_float64
|
If
TYPE:
|
gram_dtype
|
Dtype the per-chunk Gram matmuls run in. Default
TYPE:
|
| ATTRIBUTE | DESCRIPTION |
|---|---|
weight |
Weight matrix of shape
TYPE:
|
bias |
Bias vector of shape
TYPE:
|
alpha |
L2 regularization strength.
TYPE:
|
n_seen |
Number of samples accumulated so far (across all chunks).
TYPE:
|
Examples:
Fit over three chunks of a long sequence then finalize:
>>> readout = IncrementalRidgeReadoutLayer(in_features=200, out_features=3)
>>> for states_chunk, targets_chunk in chunks:
... readout.partial_fit(states_chunk, targets_chunk)
>>> readout.finalize()
>>> output = readout(states_chunk)
See Also
CholeskyReadoutLayer : Single-shot Cholesky ridge readout. CGReadoutLayer : Iterative Conjugate Gradient ridge readout. resdag.training.ESNTrainer.fit_stream : Trainer streaming-over-DataLoader path.
Source code in src/resdag/layers/readouts/incremental_ridge.py
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 | |
reset_accumulators
¶
reset_accumulators() -> None
Clear all accumulated statistics and the fitted flag.
Returns the layer to its freshly-constructed state: the sufficient
statistics are zeroed, the sample count is reset to 0, and
is_fitted becomes False. Call this before re-fitting a layer
that was previously finalized.
Source code in src/resdag/layers/readouts/incremental_ridge.py
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 | |
partial_fit
¶
partial_fit(states: Tensor, targets: Tensor) -> IncrementalRidgeReadoutLayer
Accumulate the ridge sufficient statistics for one chunk.
Flattens (B, T, F) chunks to (N, F), validates shapes against
the layer's feature dimensions, and adds the chunk's contribution to the
running XtX / Xty / sum_x / sum_y / n accumulators.
Call once per DataLoader batch (or per window of a long sequence);
the centered statistics are merged so chunk boundaries do not affect the final
fit.
Calling partial_fit after finalize keeps accumulating onto
the existing statistics and clears the fitted flag — the layer must be
re-finalize\ d before it can be used for inference again. Use
reset_accumulators to start a fresh fit.
| PARAMETER | DESCRIPTION |
|---|---|
states
|
State chunk of shape
TYPE:
|
targets
|
Target chunk of shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
IncrementalRidgeReadoutLayer
|
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Source code in src/resdag/layers/readouts/incremental_ridge.py
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 | |
finalize
¶
finalize() -> None
Solve the accumulated ridge system and write the fitted weights.
Assembles the centered (when bias=True), regularised normal
equations (XᵀX + αI) W = Xᵀy from the running sufficient statistics
and solves them with a Cholesky factorisation. Recovers the un-penalised
intercept from the running means, copies the result into the layer's
weight / bias parameters, and sets is_fitted to True.
| RAISES | DESCRIPTION |
|---|---|
RuntimeError
|
If no samples have been accumulated ( |
Notes
finalize does not clear the accumulators, so it can be called
again after additional partial_fit calls to refine the fit on
more data. Call reset_accumulators to start over.
Source code in src/resdag/layers/readouts/incremental_ridge.py
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 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 | |
solve
¶
Single-shot fit: accumulate one chunk then finalize.
Provided so IncrementalRidgeReadoutLayer is a drop-in
ReadoutLayer — fit(states, targets) works exactly like the
other readouts (it resets the accumulators, accumulates the whole batch,
and solves). The hook returns the fitted coefficients so the base
fit copy-back path is reused.
| PARAMETER | DESCRIPTION |
|---|---|
states
|
Flattened state matrix of shape
TYPE:
|
targets
|
Flattened target matrix of shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
coefs
|
Coefficient matrix of shape
TYPE:
|
intercept
|
Intercept vector of shape
TYPE:
|
Source code in src/resdag/layers/readouts/incremental_ridge.py
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 | |
forward
¶
Apply the fitted linear transformation to input.
| PARAMETER | DESCRIPTION |
|---|---|
input
|
Input tensor of shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Output tensor of shape |
| RAISES | DESCRIPTION |
|---|---|
RuntimeError
|
If |
Notes
Two internal call sites legitimately run forward while unfitted and
bypass the guard via the private _allow_unfitted_forward flag:
pytorch_symbolic graph construction (which traces output shapes by
calling forward once with placeholder data) and the trainer's
streaming accumulation pass (where the readout's forward only flows a
value downstream while a pre-hook accumulates statistics). Genuine
inference always goes through the guard.
Under torch.compile (the compiled forecast fast path captures this
forward directly and calls it per autoregressive step) the entire
Python guard is skipped: it would otherwise force a dynamo graph break
on every step and silently drop the model to the ~14x-slower eager
rollout. Fittedness is still enforced before the compiled loop by the
eager teacher-forced warmup pass that forecast always runs first: it
executes the full graph — including this readout's eager forward —
which trips the guard for a genuinely-unfitted readout. So skipping the
per-step guard under compile removes a redundant check, not a safety net.
The fittedness check itself reads the sync-free _fitted_flag mirror
(see resdag.layers.readouts.ReadoutLayer.is_fitted), never the
_is_fitted buffer's .item(), so even the eager per-step path
pays no device->host sync.
Source code in src/resdag/layers/readouts/incremental_ridge.py
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 | |
IncrementalRidgeReadout
¶
Bases: IncrementalRidgeReadoutLayer
Deprecated alias for IncrementalRidgeReadoutLayer.
Retained for backward compatibility. Instantiating this class emits a
DeprecationWarning and constructs an
IncrementalRidgeReadoutLayer; the two are otherwise identical
(IncrementalRidgeReadout is a subclass, so
isinstance(IncrementalRidgeReadout(...), IncrementalRidgeReadoutLayer)
holds).
Deprecated.
Use IncrementalRidgeReadoutLayer instead.
IncrementalRidgeReadout will be removed in a future release.
See Also
IncrementalRidgeReadoutLayer : The canonical class this aliases.
Source code in src/resdag/layers/readouts/incremental_ridge.py
583 584 585 586 587 588 589 590 | |
RLSReadout
¶
RLSReadout(
in_features: int,
out_features: int,
bias: bool = True,
name: str | None = None,
trainable: bool = False,
*,
forgetting: float = 1.0,
delta: float | None = None,
alpha: float | None = None,
use_float64: bool = True,
device: device | None = None,
dtype: dtype | None = None
)
Bases: ReadoutLayer
True-online Recursive Least Squares (RLS) readout with forgetting.
Refines the readout weights one sample at a time from a running inverse-correlation matrix \(P\), instead of solving a batch linear system. This makes it the natural readout for streaming and non-stationary reservoir computing: samples can arrive indefinitely, and a forgetting factor \(\lambda < 1\) lets the readout track a target whose statistics drift over time.
Update equations
For each feature vector \(x_t \in \mathbb{R}^F\) with target
\(d_t \in \mathbb{R}^O\), writing \(W \in \mathbb{R}^{F \times O}\)
for the transpose of the nn.Linear weight and \(P \in \mathbb{R}^{F \times F}\) for the inverse correlation:
The a-priori error \(e_t\) uses the current weights (before this
step's update), which is what makes the recursion equivalent to an
exponentially-weighted least-squares solve at every step. The rank-1
\(P\) update preserves symmetry in exact arithmetic, so \(P\) is
re-symmetrised periodically — every _RESYM_EVERY steps plus once at
the end of each pass — to control floating-point drift without paying a
full transpose-copy on every step.
Relationship to ridge
- \(\lambda = 1\) (the default) is growing-window RLS: every past
sample keeps unit weight, so after enough data the fit converges to the
ordinary least-squares solution — equivalently ridge with
\(\alpha \to 0\), the \(\delta\) prior washing out as evidence
accumulates. A fully-streamed \(\lambda = 1\) fit therefore agrees with
a batch
RidgeReadoutLayer(smallalpha) fit on the same data to a tight tolerance. - \(\lambda < 1\) forgets: sample \(t - \tau\) is weighted \(\lambda^{\tau}\), giving an effective memory of \(1 / (1 - \lambda)\) samples. Use it when the input/target relation is non-stationary; there is no batch-ridge equivalent.
Because RLS is inherently sequential (each \(P_t\), \(W_t\) depends
on its predecessor), partial_fit applies the updates in row-major
stream order: a (B, T, F) batch is flattened to (B * T, F) and
consumed one step at a time, exactly as ReadoutLayer.fit flattens.
| PARAMETER | DESCRIPTION |
|---|---|
in_features
|
Size of input features
TYPE:
|
out_features
|
Size of output features
TYPE:
|
bias
|
Whether to include a bias term. When
TYPE:
|
name
|
Name for this readout layer. Used for identification in multi-readout
architectures and as the key into
TYPE:
|
trainable
|
If
TYPE:
|
forgetting
|
The forgetting factor \(\lambda \in (0, 1]\).
TYPE:
|
delta
|
Initialises \(P = I / \delta\) (default
TYPE:
|
alpha
|
Alias for
TYPE:
|
use_float64
|
If
TYPE:
|
device
|
Device for the layer parameters and the
TYPE:
|
dtype
|
Dtype for the
TYPE:
|
| ATTRIBUTE | DESCRIPTION |
|---|---|
weight |
Weight matrix of shape
TYPE:
|
bias |
Bias vector of shape
TYPE:
|
P |
The
TYPE:
|
forgetting |
The forgetting factor \(\lambda\).
TYPE:
|
delta |
The \(P\) initialisation constant.
TYPE:
|
n_seen |
Number of samples applied across all
TYPE:
|
Examples:
Stream a stationary problem to convergence, then predict:
>>> readout = RLSReadout(in_features=200, out_features=3, forgetting=1.0)
>>> for states_chunk, targets_chunk in chunks:
... readout.partial_fit(states_chunk, targets_chunk)
>>> output = readout(states_chunk)
Fresh online fit in one call (resets P first):
>>> readout.fit_online(states, targets)
See Also
IncrementalRidgeReadoutLayer : Streaming ridge via sufficient statistics. RidgeReadoutLayer : Batch closed-form ridge readout. resdag.training.ESNTrainer : Trainer that uses this for fitting.
References
[1] S. Haykin, "Adaptive Filter Theory," 5th ed., Pearson, 2014, ch. 10.
Source code in src/resdag/layers/readouts/rls_readout.py
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 | |
reset_state
¶
reset_state() -> None
Reset the recursion: P = I / delta, zero the weights and sample count.
Returns the layer to its freshly-constructed online state — P is
reinitialised to I / delta, the weight / bias parameters are
zeroed, the sample count is cleared, and is_fitted becomes
False. Call this before starting a fresh stream; fit_online
calls it for you.
Source code in src/resdag/layers/readouts/rls_readout.py
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 | |
partial_fit
¶
partial_fit(states: Tensor, targets: Tensor) -> RLSReadout
Apply the RLS recursion over one chunk, continuing the current stream.
Flattens a (B, T, F) chunk to (N, F) (row-major, matching
ReadoutLayer.fit), validates shapes and finiteness, and runs the
rank-1 RLS update once per sample in stream order. State (P and
the weights) is carried across calls, so feeding a long sequence in
chunks is identical to feeding it whole — call reset_state (or
fit_online) to start a fresh stream.
| PARAMETER | DESCRIPTION |
|---|---|
states
|
State chunk of shape
TYPE:
|
targets
|
Target chunk of shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
RLSReadout
|
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Source code in src/resdag/layers/readouts/rls_readout.py
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 | |
fit_online
¶
fit_online(states: Tensor, targets: Tensor) -> RLSReadout
Reset the recursion and stream-fit the whole (states, targets) pair.
A readable one-call entry point that mirrors
IncrementalRidgeReadoutLayer's ergonomics: it clears any prior
recursion state (reset_state) and then partial_fit\ s the
full input. Use it for a fresh online fit over a single sequence; use
partial_fit directly to continue an existing stream.
| PARAMETER | DESCRIPTION |
|---|---|
states
|
State matrix of shape
TYPE:
|
targets
|
Target matrix of shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
RLSReadout
|
|
Source code in src/resdag/layers/readouts/rls_readout.py
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 | |
solve
¶
Single-shot batch fit: reset the recursion and stream the whole pass.
Provided so RLSReadout is a drop-in ReadoutLayer —
fit(states, targets) (and hence ESNTrainer) works exactly
like the other readouts. This is the honest single-shot behaviour for
an online algorithm: it resets P and applies the RLS recursion over
the entire (already-flattened) batch once, in stream order. For
\(\lambda = 1\) and enough samples this recovers the ordinary
least-squares fit; it is not a closed-form ridge solve.
| PARAMETER | DESCRIPTION |
|---|---|
states
|
Flattened state matrix of shape
TYPE:
|
targets
|
Flattened target matrix of shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
coefs
|
Coefficient matrix of shape
TYPE:
|
intercept
|
Intercept vector of shape
TYPE:
|
Source code in src/resdag/layers/readouts/rls_readout.py
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 | |
FISTAReadoutLayer
¶
FISTAReadoutLayer(
in_features: int,
out_features: int,
bias: bool = True,
name: str | None = None,
trainable: bool = False,
*,
alpha: float = 0.001,
l1_ratio: float = 1.0,
max_iter: int = 1000,
tol: float = 1e-06,
use_float64: bool = True,
gram_dtype: dtype | None = None,
power_iters: int = 0,
power_iter_margin: float = 0.05
)
Bases: ReadoutLayer
Sparse / robust readout via L1 (lasso) or elastic-net FISTA.
Solves the elastic-net least-squares problem
(rho = l1_ratio) with the accelerated proximal-gradient method FISTA
[1], batched across every output column simultaneously. l1_ratio=1
gives pure lasso (maximally sparse); l1_ratio=0 gives pure ridge, in
which case FISTA converges to the same solution as
RidgeReadoutLayer. The intercept is recovered by centering and is
left un-penalised.
Objective and sklearn parameterisation
This layer minimises the un-normalised sum-of-squares objective above.
sklearn.linear_model.ElasticNet instead minimises a
sample-size-normalised objective:
and sklearn.linear_model.Lasso(alpha=a) is the l1_ratio=1 special
case, i.e. it minimises
\(\tfrac{1}{2N}\lVert X w - y\rVert^2 + a\,\lVert w\rVert_1\).
Multiplying sklearn's objective by 2 N shows the two objectives
coincide when
where N is the number of (flattened) samples. So to reproduce a
Lasso(alpha=a) / ElasticNet(alpha=a, l1_ratio=rho) fit with this
layer, pass alpha = 2 * N * a (and the same l1_ratio). This scaling
is what makes the FISTA coefficients match sklearn's to solver tolerance;
see the tests for the round-trip.
FISTA details
The smooth part \(f(W) = \lVert X W - Y\rVert^2 + \tfrac{1}{2}\alpha(1-\rho)\lVert W\rVert^2\) has gradient \(2 X^\top X W - 2 X^\top Y + \alpha(1-\rho) W\), and the non-smooth L1 part has the soft-threshold proximal operator \(\operatorname{prox}(Z) = \operatorname{sign}(Z)\max(|Z| - \tau, 0)\) with threshold \(\tau = \text{step}\cdot\alpha\,\rho\). The constant step size is \(1/L\) with Lipschitz constant
where \(\lambda_{\max}\) is the top eigenvalue of the Gram, obtained
from torch.linalg.eigvalsh (small (F, F) system) or, when
power_iters > 0, a few power iterations. Momentum follows the standard
recurrence \(t_{k+1} = (1 + \sqrt{1 + 4 t_k^2})/2\). Iteration stops on
the relative change \(\lVert W_{k+1} - W_k\rVert / \lVert W_k\rVert < \text{tol}\) or after max_iter steps (a non-converged run warns).
Only the Gram \(X^\top X\) and \(X^\top Y\) enter the iteration, so
the per-step cost is one (F, F) @ (F, T) matmul independent of the
sample count N — cheap for the readout widths typical of reservoir
computing.
| PARAMETER | DESCRIPTION |
|---|---|
in_features
|
Size of input features (reservoir state dimension).
TYPE:
|
out_features
|
Size of output features (prediction dimension).
TYPE:
|
bias
|
Whether to include a bias term. When
TYPE:
|
name
|
Name for this readout layer. Used for identification in multi-readout
architectures and as the key into
TYPE:
|
trainable
|
If
TYPE:
|
alpha
|
Overall regularisation strength (must be non-negative). See the
parameterisation note above for the relation to sklearn's
TYPE:
|
l1_ratio
|
Elastic-net mixing in
TYPE:
|
max_iter
|
Maximum number of FISTA iterations.
TYPE:
|
tol
|
Relative-change convergence tolerance on the coefficient matrix. A run
that reaches
TYPE:
|
use_float64
|
If
TYPE:
|
gram_dtype
|
Dtype for forming the Gram matrix and right-hand side (the heavy
TYPE:
|
power_iters
|
If
TYPE:
|
power_iter_margin
|
Initial margin applied to a power-iteration eigenvalue estimate.
TYPE:
|
| ATTRIBUTE | DESCRIPTION |
|---|---|
weight |
Weight matrix of shape
TYPE:
|
bias |
Bias vector of shape
TYPE:
|
alpha |
Overall regularisation strength.
TYPE:
|
l1_ratio |
Elastic-net mixing parameter.
TYPE:
|
n_iter_ |
Number of FISTA iterations run by the last
TYPE:
|
converged_ |
Whether the last
TYPE:
|
Examples:
>>> readout = FISTAReadoutLayer(in_features=200, out_features=3, alpha=1e-2)
>>> states = torch.randn(8, 50, 200) # (batch, time, features)
>>> targets = torch.randn(8, 50, 3)
>>> readout.fit(states, targets)
>>> output = readout(states)
>>> output.shape
torch.Size([8, 50, 3])
See Also
RidgeReadoutLayer : Direct ridge (L2-only) readout. SVDReadoutLayer : SVD filter-factor readout. resdag.training.ESNTrainer : Trainer that uses this for fitting.
References
[1] A. Beck and M. Teboulle, "A Fast Iterative Shrinkage-Thresholding Algorithm for Linear Inverse Problems," SIAM J. Imaging Sci., 2(1), 183-202, 2009.
Source code in src/resdag/layers/readouts/fista_readout.py
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 | |
solve
¶
Solve the elastic-net readout via FISTA on flattened inputs.
| PARAMETER | DESCRIPTION |
|---|---|
states
|
Flattened state matrix of shape
TYPE:
|
targets
|
Flattened target matrix of shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
coefs
|
Coefficient matrix of shape
TYPE:
|
intercept
|
Intercept vector of shape
TYPE:
|
Source code in src/resdag/layers/readouts/fista_readout.py
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 422 423 424 | |
FISTAReadout
¶
Bases: FISTAReadoutLayer
Deprecated alias for FISTAReadoutLayer.
Retained for backward compatibility. Instantiating this class emits a
DeprecationWarning and constructs a FISTAReadoutLayer;
the two are otherwise identical (FISTAReadout is a subclass, so
isinstance(FISTAReadout(...), FISTAReadoutLayer) holds).
Deprecated.
Use FISTAReadoutLayer instead. FISTAReadout will be
removed in a future release.
See Also
FISTAReadoutLayer : The canonical class this aliases.
Source code in src/resdag/layers/readouts/fista_readout.py
459 460 461 462 463 464 465 466 | |
Transforms¶
Transforms are ordinary Torch modules. A custom pointwise transform can declare
supports_framewise=True for fast autonomous execution; temporal transforms
use the forecast capability contract.
Standardize.fit and inverse implement a reversible fitted transform.
transforms
¶
Transform Layers¶
Specialized transformation layers for advanced ESN architectures, including state augmentation, feature manipulation, and regularization.
| CLASS | DESCRIPTION |
|---|---|
Concatenate |
Concatenates multiple inputs along the feature dimension. |
ExtendedSquare |
Appends the elementwise square of every feature ( |
FeaturePartitioner |
Partitions input features into overlapping groups. |
NLAT2 |
T₂ nonlinear algebraic transform ( |
NLAT3 |
T₃ nonlinear algebraic transform ( |
Pad |
Appends a constant column to the feature dimension ( |
PartialSquare |
Squares a leading fraction (or count) of features in place. |
Power |
Per-feature exponentiation by a fixed power. |
SelectiveDropout |
Per-feature dropout with selectivity control. |
SelectiveExponentiation |
Per-feature exponentiation transformation (squares even-indexed units;
|
Standardize |
Per-feature z-score standardization with buffer-stored mean/std,
|
Examples:
>>> from resdag.layers.transforms import Concatenate, SelectiveExponentiation
>>> import torch
>>>
>>> concat = Concatenate()
>>> x1 = torch.randn(4, 100, 50)
>>> x2 = torch.randn(4, 100, 50)
>>> combined = concat(x1, x2) # (4, 100, 100)
Concatenate
¶
Bases: Module
Concatenate multiple tensors along the feature (last) dimension.
This layer takes any number of input tensors and concatenates them along the last dimension. Useful for combining outputs from parallel branches in multi-reservoir or ensemble architectures.
All input tensors must have the same shape except for the last dimension (features).
| ATTRIBUTE | DESCRIPTION |
|---|---|
None |
This layer has no learnable parameters.
|
Examples:
Basic concatenation:
>>> import torch
>>> from resdag.layers.transforms import Concatenate
>>>
>>> concat = Concatenate()
>>> x1 = torch.randn(32, 50, 100) # (batch, time, features1)
>>> x2 = torch.randn(32, 50, 200) # (batch, time, features2)
>>> y = concat(x1, x2)
>>> print(y.shape)
torch.Size([32, 50, 300])
Multiple inputs:
>>> x3 = torch.randn(32, 50, 50)
>>> y = concat(x1, x2, x3)
>>> print(y.shape)
torch.Size([32, 50, 350])
See Also
FeaturePartitioner : Splits features into overlapping partitions.
forward
¶
Concatenate input tensors along the last dimension.
| PARAMETER | DESCRIPTION |
|---|---|
*inputs
|
Variable number of input tensors to concatenate. All tensors must have the same shape except for the last dimension.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Concatenated tensor with combined feature dimension. |
| RAISES | DESCRIPTION |
|---|---|
RuntimeError
|
If tensors have incompatible shapes for concatenation. |
Examples:
>>> concat = Concatenate()
>>> a = torch.randn(4, 10, 20)
>>> b = torch.randn(4, 10, 30)
>>> result = concat(a, b)
>>> print(result.shape)
torch.Size([4, 10, 50])
Source code in src/resdag/layers/transforms/concatenate.py
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 | |
ExtendedSquare
¶
Bases: Module
Append the elementwise square of every feature: [x, x**2].
Concatenates the input with its elementwise square along the last dimension,
mapping x of shape (..., F) to [x, x ** 2] of shape
(..., 2F). Doubling the state with squared copies breaks the odd
symmetry of a tanh reservoir (which otherwise cannot represent even
functions of its inputs), enriching the features seen by the readout.
This is the ResDAG equivalent of ExtendedSquare in
ReservoirComputing.jl (SciML/ReservoirComputing.jl, src/states.jl),
introduced by Herteux & Räth, "Breaking symmetries of the reservoir
equations in echo state networks", Chaos 30, 123142 (2020),
10.1063/5.0028993. RC.jl stacks the squared block below the linear
block of the (feature-major) state; here features live on the last axis, so
the squared block is concatenated along dim=-1.
Notes
This layer has no configuration and no learnable parameters.
Examples:
>>> import torch
>>> from resdag.layers.transforms import ExtendedSquare
>>>
>>> layer = ExtendedSquare()
>>> x = torch.tensor([[1.0, 2.0, 3.0]])
>>> layer(x)
tensor([[1., 2., 3., 1., 4., 9.]])
The feature dimension is doubled:
>>> ExtendedSquare()(torch.randn(2, 5, 4)).shape
torch.Size([2, 5, 8])
See Also
Power : Exponentiates every feature in place (no concatenation). PartialSquare : Squares only a leading fraction of features in place. Pad : Appends a single constant column.
forward
¶
Concatenate input with its elementwise square along dim=-1.
Rank-agnostic on the feature (last) dimension: (batch, features),
(batch, time, features) and any higher rank are all accepted, so the
layer works in both the full-sequence and the single-step autoregressive
forecast paths.
| PARAMETER | DESCRIPTION |
|---|---|
input
|
Tensor of shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Tensor of shape |
Source code in src/resdag/layers/transforms/extended_square.py
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | |
FeaturePartitioner
¶
Bases: Module
A layer that partitions the feature dimension into overlapping slices.
This layer is useful for dividing input features into structured regions while maintaining smooth transitions between partitions. Commonly used in parallel reservoir architectures where different reservoirs process different feature subspaces.
Behavior:
- Splits the feature dimension into partitions groups
- Each partition overlaps with its neighbors by overlap units
- Applies circular wrapping: last overlap features wrap to start, and vice versa
Args: partitions: Number of partitions to divide the feature dimension into overlap: Overlap size (in feature units) for each partition
Input Shape:
(..., features) — rank-agnostic on the feature (last) dimension. Both
(batch, features) and (batch, sequence_length, features) are accepted;
the leading dimensions are preserved. The 2-D rank lets the layer sit in
the autoregressive forecast path, where the flattened engine feeds
single-step slices.
Output:
List of partitions tensors, each with the same leading dimensions as
the input and a last dimension of
partition_width = features // partitions + 2 * overlap
Raises:
ValueError: At construction, if partitions < 1 or overlap < 0.
ValueError: At forward, if features % partitions != 0 (unless partitions == 1).
ValueError: At forward, if overlap >= features // partitions (invalid overlap size).
Warns:
UserWarning: At construction, if partitions == 1 and overlap > 0,
since the single-partition fast path returns the input unchanged and
the overlap is silently ignored.
Example: >>> partitioner = FeaturePartitioner(partitions=2, overlap=1) >>> x = torch.arange(12).reshape(1, 1, 12).float() >>> outputs = partitioner(x) >>> len(outputs) 2 >>> outputs[0].shape torch.Size([1, 1, 8]) # 12//2 + 2*1 = 8
Configuration is validated eagerly so misconfiguration surfaces at
construction rather than deep inside a forward pass (the layer lives in
an eagerly-resolved symbolic graph). The divisibility and
overlap-vs-width checks stay in forward, where the runtime
feature count is known.
Args: partitions: Number of partitions (must be a positive integer) overlap: Overlap size between adjacent partitions (must be non-negative)
Raises:
ValueError: If partitions < 1 or overlap < 0.
Warns:
UserWarning: If partitions == 1 and overlap > 0 — the
single-partition fast path returns the input unchanged, so the
overlap has no effect.
Source code in src/resdag/layers/transforms/feature_partitioner.py
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 | |
forward
¶
Split the feature dimension into overlapping partitions with circular wrapping.
Operates purely on the feature (last) dimension, so it is rank-agnostic:
both 2-D (batch, features) and 3-D (batch, sequence_length, features)
inputs are accepted (the latter is the usual sequence layout; the former
is what the flattened single-step forecast engine feeds per step). The
leading dimensions are preserved unchanged.
Args: input: Input tensor whose last dimension is the feature dimension, e.g. (batch, features) or (batch, sequence_length, features)
Returns:
List of length self.partitions, each with the same leading
dimensions as input and a last dimension of partition_width
Raises: ValueError: If feature dimension is not divisible by partitions ValueError: If overlap is too large relative to partition size
Source code in src/resdag/layers/transforms/feature_partitioner.py
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 | |
NLAT2
¶
Bases: Module
T₂ nonlinear algebraic transform: out[i] = x[i-1] * x[i-2].
Replaces each even-0-based feature i ≥ 2 with the product of its two
preceding features and leaves every other feature unchanged, keeping the
feature dimension the same. Introducing products of neighbouring states adds
even nonlinear structure to a tanh reservoir without growing the state.
This is the ResDAG equivalent of NLAT2 in ReservoirComputing.jl
(SciML/ReservoirComputing.jl, src/states.jl), the T₂ algorithm of
Chattopadhyay, Hassanzadeh & Subramanian, "Data-driven predictions of a
multiscale Lorenz 96 chaotic system using machine-learning methods:
reservoir computing, artificial neural network, and long short-term memory
network", Nonlinear Processes in Geophysics 27, 373–389 (2020),
10.5194/npg-27-373-2020. RC.jl's 1-based rule
(idx > 1 and isodd(idx): x[idx] = x[idx-1] * x[idx-2]) maps to
the 0-based rule above; the two agree element-for-element on RC.jl's own
worked example (see module docstring).
The transform is shape-static: which features are rewritten depends only on the (static) feature dimension, never on the input values, so the forward is branch-free over the data and torch.compile-friendly.
Notes
This layer has no configuration and no learnable parameters.
Examples:
>>> import torch
>>> from resdag.layers.transforms import NLAT2
>>>
>>> layer = NLAT2()
>>> x = torch.arange(10.0).reshape(1, 10)
>>> layer(x)
tensor([[ 0., 1., 0., 3., 6., 5., 20., 7., 42., 9.]])
See Also
NLAT3 : T₃ transform using the surrounding neighbours x[i-1] * x[i+1].
SelectiveExponentiation : T₁/NLAT1 (square every even-0-based feature).
forward
¶
Rewrite even features i ≥ 2 as x[i-1] * x[i-2] along dim=-1.
Rank-agnostic on the feature (last) dimension: (batch, features),
(batch, time, features) and higher ranks are all accepted, so the
layer works in both the full-sequence and single-step autoregressive
forecast paths. Feature dimensions below 3 have no eligible
position and pass through unchanged.
| PARAMETER | DESCRIPTION |
|---|---|
input
|
Tensor of shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Same shape as input; selected features hold the neighbour product
|
Source code in src/resdag/layers/transforms/nlat.py
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 | |
NLAT3
¶
Bases: Module
T₃ nonlinear algebraic transform: out[i] = x[i-1] * x[i+1].
Replaces each even-0-based feature i in the interior (2 ≤ i ≤ N-2)
with the product of its immediately preceding and following features and
leaves every other feature unchanged, keeping the feature dimension the
same. Like NLAT2 it injects even nonlinear structure into a
tanh reservoir, but couples each feature to both of its neighbours.
This is the ResDAG equivalent of NLAT3 in ReservoirComputing.jl
(SciML/ReservoirComputing.jl, src/states.jl), the T₃ algorithm of
Chattopadhyay, Hassanzadeh & Subramanian, "Data-driven predictions of a
multiscale Lorenz 96 chaotic system using machine-learning methods:
reservoir computing, artificial neural network, and long short-term memory
network", Nonlinear Processes in Geophysics 27, 373–389 (2020),
10.5194/npg-27-373-2020. RC.jl's 1-based rule
(1 < idx < N and isodd(idx): x[idx] = x[idx-1] * x[idx+1]) maps
to the 0-based rule above; the last eligible feature is excluded when it has
no right neighbour, matching RC.jl's idx < lastindex guard. The two
agree element-for-element on RC.jl's own worked example (see module
docstring).
The transform is shape-static: which features are rewritten depends only on the (static) feature dimension, never on the input values, so the forward is branch-free over the data and torch.compile-friendly.
Notes
This layer has no configuration and no learnable parameters.
Examples:
>>> import torch
>>> from resdag.layers.transforms import NLAT3
>>>
>>> layer = NLAT3()
>>> x = torch.arange(10.0).reshape(1, 10)
>>> layer(x)
tensor([[ 0., 1., 3., 3., 15., 5., 35., 7., 63., 9.]])
See Also
NLAT2 : T₂ transform using the two preceding neighbours x[i-1] * x[i-2].
SelectiveExponentiation : T₁/NLAT1 (square every even-0-based feature).
forward
¶
Rewrite interior even features as x[i-1] * x[i+1] along dim=-1.
Rank-agnostic on the feature (last) dimension: (batch, features),
(batch, time, features) and higher ranks are all accepted, so the
layer works in both the full-sequence and single-step autoregressive
forecast paths. Feature dimensions below 3 have no eligible
interior position and pass through unchanged.
| PARAMETER | DESCRIPTION |
|---|---|
input
|
Tensor of shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Same shape as input; selected interior features hold the neighbour
product |
Source code in src/resdag/layers/transforms/nlat.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 | |
Pad
¶
Pad(padding: float = 1.0)
Bases: Module
Append a constant column to the feature dimension.
Concatenates a fixed constant (default 1.0) as one extra feature at the
end of the last dimension, mapping x of shape (..., F) to
[x, padding] of shape (..., F + 1). This is a bias-like augmentation:
a constant reservoir feature lets an affine readout absorb an intercept term
directly from the state.
This is the ResDAG equivalent of Pad in ReservoirComputing.jl
(SciML/ReservoirComputing.jl, src/states.jl). RC.jl appends the padding
as a trailing row of the (feature-major) state matrix; here features live on
the last axis, so the constant is appended along dim=-1.
| PARAMETER | DESCRIPTION |
|---|---|
padding
|
Constant value appended as the extra feature.
TYPE:
|
Examples:
>>> import torch
>>> from resdag.layers.transforms import Pad
>>>
>>> layer = Pad()
>>> x = torch.tensor([[0.0, 1.0, 2.0, 3.0]])
>>> layer(x)
tensor([[0., 1., 2., 3., 1.]])
A custom padding value:
>>> Pad(padding=-2.0)(torch.zeros(2, 5, 3)).shape
torch.Size([2, 5, 4])
See Also
ExtendedSquare : Appends the elementwise square of every feature. Concatenate : Concatenates arbitrary tensors along the feature dimension.
| PARAMETER | DESCRIPTION |
|---|---|
padding
|
Constant value appended as the trailing feature.
TYPE:
|
Source code in src/resdag/layers/transforms/pad.py
51 52 53 54 55 56 57 58 59 60 | |
forward
¶
Append the constant padding column along the last dimension.
Rank-agnostic on the feature (last) dimension: (batch, features),
(batch, time, features) and any higher rank are all accepted, so the
layer sits in both the full-sequence and the single-step autoregressive
forecast paths. The padding column inherits the device and dtype of
input.
| PARAMETER | DESCRIPTION |
|---|---|
input
|
Tensor of shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Tensor of shape |
Source code in src/resdag/layers/transforms/pad.py
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 | |
PartialSquare
¶
Bases: Module
Square a leading fraction (or count) of features, leave the rest.
Squares the first k features of the last dimension in place and passes
the remaining F - k features through unchanged, keeping the feature
dimension the same. k is either a fixed integer count or a fraction
eta of the feature dimension, k = floor(eta * F). Squaring only part
of the state is a symmetry-aware augmentation: it injects the even
nonlinearity needed to break the odd symmetry of a tanh reservoir while
leaving a linear subspace intact, which improves conditioning versus
squaring everything.
This is the ResDAG equivalent of PartialSquare in
ReservoirComputing.jl (SciML/ReservoirComputing.jl, src/states.jl),
from Barbosa et al., "Symmetry-aware reservoir computing", Phys. Rev. E
104, 045307 (2021), 10.1103/PhysRevE.104.045307. RC.jl squares the
leading floor(eta * N) entries of the (feature-major) state vector; here
features live on the last axis, so the leading block of dim=-1 is
squared. The 0-based ResDAG threshold i < floor(eta * F) reproduces the
1-based RC.jl condition idx <= floor(eta * N) element-for-element.
| PARAMETER | DESCRIPTION |
|---|---|
eta
|
If a |
Examples:
Fractional eta squares a leading fraction of the features:
>>> import torch
>>> from resdag.layers.transforms import PartialSquare
>>>
>>> layer = PartialSquare(0.6)
>>> x = torch.arange(10.0).reshape(1, 10)
>>> layer(x)
tensor([[ 0., 1., 4., 9., 16., 25., 6., 7., 8., 9.]])
An integer eta squares exactly that many leading features:
>>> PartialSquare(3)(torch.tensor([[2.0, 2.0, 2.0, 2.0]]))
tensor([[4., 4., 4., 2.]])
See Also
ExtendedSquare : Appends the square of every feature (doubles the dim). Power : Exponentiates every feature by a fixed power. SelectiveExponentiation : Parity-selective (even/odd index) exponentiation.
| PARAMETER | DESCRIPTION |
|---|---|
eta
|
A |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
TypeError
|
If |
Source code in src/resdag/layers/transforms/partial_square.py
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 | |
forward
¶
Square the leading k features; pass the rest through unchanged.
The split point k is data-independent (it depends only on the static
feature dimension and eta), so the branch-free where(mask, x*x, x)
gate is torch.compile-friendly and rank-agnostic on the last dimension:
(batch, features), (batch, time, features) and higher ranks are
all accepted, covering both the full-sequence and single-step
autoregressive forecast paths.
| PARAMETER | DESCRIPTION |
|---|---|
input
|
Tensor of shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Same shape as input; the first |
Source code in src/resdag/layers/transforms/partial_square.py
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 | |
Power
¶
Bases: Module
Exponentiate every feature to a fixed power.
Applies the chosen power element-wise along the last dimension. Used in power-augmented ESN architectures to enrich reservoir states before readout.
| PARAMETER | DESCRIPTION |
|---|---|
exponent
|
Power applied to each element of the input tensor.
TYPE:
|
sign_preserving
|
If
TYPE:
|
Notes
With sign_preserving=False (the default), torch.pow has two
edge cases that silently corrupt readout inputs on common reservoir states:
- A negative base with a non-integer exponent produces
nanin both the forward and backward pass (the realpowis undefined there). For example,Power(0.5)on[[-4.0, 4.0]]yields[[nan, 2.0]]. - A zero base with a negative exponent produces
inf(division by zero). For example,Power(-1.0)on[[0.0, 2.0]]yields[[inf, 0.5]].
Tanh reservoir states live in [-1, 1] and routinely include negative
and zero values, so a non-integer exponent on raw states is a plausible
augmentation choice that silently emits nan/inf with no diagnostic.
Use sign_preserving=True to apply sign(x) * abs(x) ** exponent,
which stays finite for negative bases (the zero base with a negative
exponent is still inf — abs(0) ** -1 diverges — and is unaffected
by sign preservation). For integer exponents the two modes are identical
for non-negative bases and differ only in sign for negative bases raised to
an odd integer power. Every integer exponent — even ones map negatives to
non-negative values, odd ones (including the power_augmented default
exponent=3.0) preserve sign — is safe in either mode.
Examples:
>>> layer = Power(exponent=2.0)
>>> x = torch.tensor([[1.0, 2.0, 3.0, 4.0]])
>>> layer(x)
tensor([[ 1., 4., 9., 16.]])
Sign-preserving mode keeps negative bases finite under a fractional
exponent, where plain torch.pow would return nan:
>>> layer = Power(exponent=0.5, sign_preserving=True)
>>> x = torch.tensor([[-4.0, 4.0, -9.0, 9.0]])
>>> layer(x)
tensor([[-2., 2., -3., 3.]])
| PARAMETER | DESCRIPTION |
|---|---|
exponent
|
Value the input is raised to for every element.
TYPE:
|
sign_preserving
|
If
TYPE:
|
Source code in src/resdag/layers/transforms/power.py
68 69 70 71 72 73 74 75 76 77 78 79 80 81 | |
forward
¶
Raise the input to self.exponent.
| PARAMETER | DESCRIPTION |
|---|---|
input
|
Tensor of shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Same shape as input, with each element raised to |
Source code in src/resdag/layers/transforms/power.py
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 | |
SelectiveDropout
¶
Bases: Module
Layer that zeros out specific features based on a fixed mask.
This layer zeros out features at specified indices across all timesteps and batches. Unlike standard dropout which is stochastic, this layer uses a fixed mask provided at initialization. Useful for ablation studies and feature importance analysis.
Args: mask: Boolean mask where True indicates features to zero out. Can be array-like (list, numpy array) or torch.Tensor of shape (features,)
Input Shape:
(batch, features) or (batch, timesteps, features) — the mask is applied
on the feature (last) dimension, so both ranks are accepted. The
autoregressive resdag.core.ESNModel.forecast engine drives the
graph one timestep at a time, which is why per-step layers must accept
the singleton-time slice as well as the full sequence.
Output Shape: Same shape as the input.
Example: >>> import numpy as np >>> mask = np.array([False, True, False, True]) # Drop indices 1 and 3 >>> layer = SelectiveDropout(mask) >>> x = torch.randn(2, 5, 4) >>> y = layer(x) >>> # Features at indices 1 and 3 are zeroed out
Args: mask: Boolean mask indicating which features to zero out (True = drop)
Raises: ValueError: If mask is not 1-dimensional
Source code in src/resdag/layers/transforms/selective_dropout.py
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | |
forward
¶
Apply selective dropout using the stored mask.
Handles both 2-D (batch, features) and 3-D
(batch, timesteps, features) inputs — the mask broadcasts over the
feature (last) dimension, mirroring resdag.layers.readouts.ReadoutLayer.
Accepting the 2-D rank lets the layer sit in the autoregressive forecast
path, where the flattened engine feeds single-step slices.
Args: input: Input tensor of shape (batch, features) or (batch, timesteps, features)
Returns: Input tensor (same shape) with masked features set to zero
Raises: ValueError: If input is neither 2-D nor 3-D, or the mask size does not match the feature dimension
Source code in src/resdag/layers/transforms/selective_dropout.py
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 | |
SelectiveExponentiation
¶
Bases: Module
Exponentiate even or odd feature indices based on parity.
If index is even, even positions in the last dimension are raised to
exponent; if index is odd, odd positions are exponentiated. Other
elements are unchanged. Used in Ott-style state-augmented ESNs.
With index=0, exponent=2 this is the T₁ / NLAT1 nonlinear algebraic
transform — squaring every even-0-based feature — of Chattopadhyay,
Hassanzadeh & Subramanian (2020) and Pathak et al. (2017), matching
NLAT1 in ReservoirComputing.jl (which squares the odd entries of a
1-based feature-major state; those are the even-0-based features here). Its
T₂/T₃ siblings are resdag.layers.transforms.NLAT2 and
resdag.layers.transforms.NLAT3.
The transform is implemented with a torch.where gate so that
unselected positions never enter the pow node: they pass through with a
gradient of 1 and are never poisoned by the pow backward (which is
inf/nan at x = 0 for exponent < 1). The base fed to pow
is also masked to a safe constant at unselected positions, which keeps
unselected gradients finite even when those positions hold negative bases
under a non-integer exponent.
The parity mask depends only on (feature_dim, device) — never on the
input values or dtype — so it is computed once per (dim, device) pair and
cached. This keeps the autoregressive forecast loop (which calls this
layer once per step) off the per-step arange/parity/ones_like
allocation path. The cache is a plain dict that stays out of state_dict
and named_buffers; it is rebuilt lazily when a new dim or device is seen.
For the common integer exponent=2 with sign_preserving=False the
forward reduces to where(mask, x * x, x) (x * x is bit-identical to
pow(x, 2) and finite everywhere, so the safe-base masking is
unnecessary); the full safe-base path is retained for every other case.
| PARAMETER | DESCRIPTION |
|---|---|
index
|
Parity selector: even
TYPE:
|
exponent
|
Power applied to the selected positions.
TYPE:
|
sign_preserving
|
If
TYPE:
|
Notes
With sign_preserving=False and a non-integer exponent, selected
positions holding a negative value produce nan in both the forward
and backward pass — this is the mathematically correct behaviour of a real
pow and matches torch.pow. Unselected positions are always
finite. For integer exponents (including the default ott_esn path,
exponent=2.0) the two modes are identical for non-negative bases and
differ only in sign for negative bases raised to an odd integer power.
Examples:
>>> layer = SelectiveExponentiation(index=2, exponent=2.0)
>>> x = torch.tensor([[1.0, 2.0, 3.0, 4.0]])
>>> layer(x)
tensor([[1., 2., 9., 4.]])
Sign-preserving mode keeps negative selected bases finite under a fractional exponent:
>>> layer = SelectiveExponentiation(index=0, exponent=0.5, sign_preserving=True)
>>> x = torch.tensor([[-4.0, 2.0, -9.0, 3.0]])
>>> layer(x)
tensor([[-2., 2., -3., 3.]])
| PARAMETER | DESCRIPTION |
|---|---|
index
|
Determines which feature indices are exponentiated (even vs odd).
TYPE:
|
exponent
|
Power applied to selected positions.
TYPE:
|
sign_preserving
|
If
TYPE:
|
Source code in src/resdag/layers/transforms/selective_exponentiation.py
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 | |
forward
¶
Apply selective exponentiation along the last dimension.
| PARAMETER | DESCRIPTION |
|---|---|
input
|
Tensor of shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Same shape as input; selected indices are raised to |
Source code in src/resdag/layers/transforms/selective_exponentiation.py
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 | |
Standardize
¶
Standardize(
num_features: int,
mean: Tensor | None = None,
std: Tensor | None = None,
eps: float = 1e-08,
)
Bases: Module
Per-feature standardization (z-score) with a learnable-free inverse.
Centers and scales each feature of the last dimension using stored
statistics, applying (x - mean) / std in forward and the exact
inverse x * std + mean in inverse. The mean and std
vectors are registered buffers of shape (num_features,), so they are
part of the state_dict and move with .to()/dtype casts and the
resdag.core.ESNModel.save_full round trip.
Statistics may be supplied at construction or estimated from data with
fit. Until either happens the layer initializes to mean = 0 and
std = 1. Supplied floating-point tensors preserve their precision and
device; both buffers use their common promoted dtype. A missing statistic
is created on the supplied tensor's device in the same dtype. Lists and
integer tensors use the default floating dtype. Two tensor statistics on
different devices are rejected rather than moved implicitly.
A finite, nonnegative eps is added to std before division to avoid
blow-up on constant (zero-variance) features; the same padded scale is used by
inverse, so inverse(forward(x)) reconstructs x to within
floating-point tolerance when the padded scale is nonzero. Setting
eps=0 disables stabilization. In float16, a positive eps is floored
at the dtype's smallest normal value, keeping the reciprocal scale
representable for constant features. Both methods are available in TorchScript.
| PARAMETER | DESCRIPTION |
|---|---|
num_features
|
Size of the feature (last) dimension this layer standardizes.
TYPE:
|
mean
|
Initial per-feature mean of shape
TYPE:
|
std
|
Finite, nonnegative initial standard deviation of shape
TYPE:
|
eps
|
Numerical-stability floor added to
TYPE:
|
| ATTRIBUTE | DESCRIPTION |
|---|---|
mean |
Registered buffer holding the per-feature mean
TYPE:
|
std |
Registered buffer holding the per-feature standard deviation
TYPE:
|
Examples:
Fit statistics from a batch, then standardize and invert:
>>> import torch
>>> from resdag.layers.transforms import Standardize
>>>
>>> layer = Standardize(num_features=3)
>>> x = torch.randn(8, 100, 3) * 5.0 + 2.0 # (batch, time, features)
>>> layer.fit(x)
Standardize(num_features=3, eps=1e-08)
>>> z = layer(x) # ~zero mean, ~unit std per feature
>>> torch.allclose(layer.inverse(z), x, atol=1e-5)
True
Inside a composable pipeline (statistics travel with save_full/.to):
>>> import pytorch_symbolic as ps
>>> from resdag import ESNModel, ESNLayer, CGReadoutLayer, Standardize
>>>
>>> norm = Standardize(num_features=3)
>>> norm.fit(torch.randn(4, 200, 3))
Standardize(num_features=3, eps=1e-08)
>>> inp = ps.Input((200, 3))
>>> normed = norm(inp)
>>> reservoir = ESNLayer(100, feedback_size=3)(normed)
>>> readout = CGReadoutLayer(100, 3, name="output")(reservoir)
>>> model = ESNModel(inp, readout)
See Also
Power : Per-feature exponentiation. SelectiveExponentiation : Parity-selective exponentiation.
| PARAMETER | DESCRIPTION |
|---|---|
num_features
|
Size of the feature dimension to standardize.
TYPE:
|
mean
|
Initial per-feature mean of shape
TYPE:
|
std
|
Initial per-feature standard deviation of shape
TYPE:
|
eps
|
Stability floor added to
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
TypeError
|
If a supplied statistic is complex or |
Source code in src/resdag/layers/transforms/standardize.py
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 | |
fit
¶
fit(input: Tensor) -> Standardize
Estimate per-feature mean and std from data and store them.
Statistics are reduced over every dimension except the last, so an
input of shape (batch, time, features) (or any number of leading
dims) yields per-feature vectors of length num_features. The
population standard deviation (unbiased=False) is used so a single
observation does not produce a nan. The fitted buffers inherit the
device/dtype of input. Validation and statistics calculation finish
before either previous buffer is replaced. Fitting inside
torch.inference_mode still permits later differentiable calls.
| PARAMETER | DESCRIPTION |
|---|---|
input
|
Data of shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Standardize
|
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If input is empty, has the wrong feature width, contains nonfinite values, or overflows while computing statistics. |
TypeError
|
If input is not a real floating-point tensor. |
Source code in src/resdag/layers/transforms/standardize.py
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 | |
forward
¶
Standardize the last dimension as (x - mean) / (std + eps).
| PARAMETER | DESCRIPTION |
|---|---|
input
|
Tensor of shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Same shape as input, centered and scaled per feature. Gradients propagate through the input using the constant stored statistics. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the last dimension of input does not equal |
Source code in src/resdag/layers/transforms/standardize.py
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 | |
inverse
¶
Invert the transform as x * (std + eps) + mean.
The exact algebraic inverse of forward, using the same
eps-padded scale so that inverse(forward(x)) == x up to
floating-point error. Use it to map standardized model outputs (e.g.
forecasts) back to the original data scale.
| PARAMETER | DESCRIPTION |
|---|---|
input
|
Standardized tensor of shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Same shape as input, mapped back to the original feature scale. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the last dimension of input does not equal |
Source code in src/resdag/layers/transforms/standardize.py
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 | |