Skip to content

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

Bases: Module, ABC

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.

state_size abstractmethod property

state_size: int

Size of the state tensor (second dimension).

output_size abstractmethod property

output_size: int

Dimensionality of the per-step output vector.

init_state abstractmethod

init_state(batch_size: int, device: device, dtype: dtype) -> Tensor

Return a zero initial state tensor.

PARAMETER DESCRIPTION
batch_size

Number of samples in the batch.

TYPE: int

device

Target device.

TYPE: device

dtype

Target dtype.

TYPE: dtype

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
@abstractmethod
def init_state(
    self,
    batch_size: int,
    device: torch.device,
    dtype: torch.dtype,
) -> torch.Tensor:
    """
    Return a zero initial state tensor.

    Parameters
    ----------
    batch_size : int
        Number of samples in the batch.
    device : torch.device
        Target device.
    dtype : torch.dtype
        Target dtype.

    Returns
    -------
    torch.Tensor
        Zero-filled initial state.
    """
    ...

forward abstractmethod

forward(inputs: list[Tensor], state: Tensor) -> tuple[Tensor, Tensor]

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 (batch, feature_dim). inputs[0] is always the feedback slice; additional elements are driving inputs.

TYPE: list[Tensor]

state

Current state tensor.

TYPE: Tensor

RETURNS DESCRIPTION
output

Per-step output of shape (batch, output_size).

TYPE: Tensor

new_state

Updated state tensor.

TYPE: Tensor

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
@abstractmethod
def forward(
    self,
    inputs: list[torch.Tensor],
    state: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
    """
    Compute the per-step output and next state from current inputs and state.

    Parameters
    ----------
    inputs : list[torch.Tensor]
        Per-timestep input slices, one per input stream, each of shape
        `(batch, feature_dim)`.  `inputs[0]` is always the feedback
        slice; additional elements are driving inputs.
    state : torch.Tensor
        Current state tensor.

    Returns
    -------
    output : torch.Tensor
        Per-step output of shape `(batch, output_size)`.
    new_state : torch.Tensor
        Updated state tensor.
    """
    ...

project_inputs

project_inputs(inputs: list[Tensor]) -> Tensor | None

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 (batch, timesteps, feature_dim). inputs[0] is the feedback sequence.

TYPE: list[Tensor]

RETURNS DESCRIPTION
Tensor or None

Precomputed projection of shape (batch, timesteps, state_size) to be consumed step-by-step via step, or None if the cell does not support the fast path (the layer then falls back to calling forward per timestep).

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
def project_inputs(self, inputs: list[torch.Tensor]) -> torch.Tensor | None:
    """
    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.

    Parameters
    ----------
    inputs : list[torch.Tensor]
        Full input sequences, one per stream, each of shape
        `(batch, timesteps, feature_dim)`.  `inputs[0]` is the
        feedback sequence.

    Returns
    -------
    torch.Tensor or None
        Precomputed projection of shape `(batch, timesteps, state_size)`
        to be consumed step-by-step via `step`, or `None` if the
        cell does not support the fast path (the layer then falls back to
        calling `forward` per timestep).
    """
    return None

step

step(projected_t: Tensor, state: Tensor) -> tuple[Tensor, Tensor]

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 (batch, state_size).

TYPE: Tensor

state

Current state tensor.

TYPE: Tensor

RETURNS DESCRIPTION
output

Per-step output.

TYPE: Tensor

new_state

Updated state tensor.

TYPE: Tensor

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
def step(
    self,
    projected_t: torch.Tensor,
    state: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
    """
    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.

    Parameters
    ----------
    projected_t : torch.Tensor
        Per-timestep slice of the precomputed projection, shape
        `(batch, state_size)`.
    state : torch.Tensor
        Current state tensor.

    Returns
    -------
    output : torch.Tensor
        Per-step output.
    new_state : torch.Tensor
        Updated state tensor.
    """
    raise NotImplementedError(
        f"{type(self).__name__} returned a projection from project_inputs() "
        f"but does not implement step()."
    )

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

RAISES DESCRIPTION
ValueError

If state does not match the expected layout. The error message names the cell class and the offending shape so callers can act on it without digging into the layer/cell internals.

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
def validate_state(self, state: torch.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.

    Parameters
    ----------
    state : torch.Tensor
        Candidate state tensor to validate.

    Raises
    ------
    ValueError
        If `state` does not match the expected layout.  The error
        message names the cell class and the offending shape so callers
        can act on it without digging into the layer/cell internals.
    """
    if state.dim() != 2 or state.shape[-1] != self.state_size:
        raise ValueError(
            f"{type(self).__name__}.validate_state: expected a 2-D state of shape "
            f"(batch, {self.state_size}); got tensor of shape {tuple(state.shape)}."
        )

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

\[ h_t = (1 - \alpha)\,h_{t-1} + \alpha\,f(W_{fb}\,x_{fb,t} + W_{in}\,x_{in,t} + W_{rec}\,h_{t-1} + b) \]

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

feedback_size

Dimension of feedback signal. Required for all ESN cells.

TYPE: int

input_size

Dimension of driving inputs. If None, no driving input weight matrix is created.

TYPE: int DEFAULT: None

spectral_radius

Target spectral radius for recurrent weights. If None, no spectral radius scaling is applied.

TYPE: float DEFAULT: None

bias

Whether to include a bias term.

TYPE: bool DEFAULT: True

bias_scaling

Scale of the random bias: entries are drawn from uniform(-bias_scaling, bias_scaling), matching the default initialization of the feedback/input weights. Ignored when bias=False. Set to 0.0 to keep a zero bias (the historical pre-0.5 behaviour, where bias=True was effectively a no-op because the bias was zero-initialized and frozen).

TYPE: float DEFAULT: 1.0

activation

Activation function for reservoir dynamics.

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

leak_rate

Leaky integration rate in (0, 1]. A scalar value of 1.0 means no leaking (standard RNN update); smaller values create slower dynamics. Values outside (0, 1] are rejected at construction with a ValueError: 0.0 would freeze the state entirely and values > 1.0 (or < 0) produce ill-defined dynamics.

A per-neuron leak rate — a 1-D tensor or sequence of length reservoir_size — assigns each unit its own timescale (heterogeneous reservoir, matching RC.jl's leak_coefficient vector). Every entry must be finite and in (0, 1]; a wrong length or any out-of-range / non-finite entry raises ValueError. A vector leak is stored as a registered buffer (_leak_rate_vec), so it moves with .to(device) / .double() and round-trips through save/load; a scalar stays a plain float with byte-identical dynamics to the pre-vector cell.

TYPE: float or 1-D tensor/sequence of shape `(reservoir_size,)` DEFAULT: 1.0

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\) = noise. Noise is applied only in training mode (self.training is True, like dropout) and is a no-op under torch.nn.Module.eval. The default 0.0 disables it entirely, leaving outputs bit-identical to the noiseless cell. The noise stream is reproducible: it is seeded deterministically from seed (independently of the weight-init draws), so a given seed reproduces the same perturbations on every run. Must be non-negative.

TYPE: float DEFAULT: 0.0

trainable

If True, reservoir weights are trainable via backpropagation. Standard ESNs use frozen (non-trainable) weights.

TYPE: bool DEFAULT: False

sparse

False keeps a dense recurrent Parameter and the ordinary dense path. True stores only CSR row indices, column indices and values as persistent buffers. weight_hh then exposes a zero-copy CSR Tensor; call weight_hh.to_dense() for an explicit dense inspection copy. Editing weight_hh.values() updates the live operator directly.

"auto" retains the size/density heuristic: at least 1,000 units on CPU or 5,000 on CUDA and density at most 0.2. This is not a calibrated speed guarantee: dense can be faster on Apple Silicon CPU. Explicit False/True always let users choose the representation.

CSR requires a frozen reservoir. Setting trainable=True later explicitly materializes dense weights and emits a warning; freeze again to restore the original sparse request. Moving to MPS uses dense weights, since MPS has no CSR operator, and returning to CPU restores CSR. Copying and checkpoints store only ordinary component arrays; the cached CSR Tensor aliases them without another weight allocation.

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 TopologyInitializer.build_sparse to avoid it. Other graph functions may allocate dense arrays internally. Collected sequence features and readout workspaces are separate memory costs.

TYPE: bool or {auto} DEFAULT: False

feedback_initializer

Initializer for the feedback weight matrix. Accepts a registry name, (name, params), any matrix-building callable, a (callable, params) tuple, or a configured initializer object.

TYPE: str, callable, tuple, or InputFeedbackInitializer DEFAULT: None

input_initializer

Initializer for the input weight matrix. Same formats as feedback_initializer. Only used when input_size is provided.

TYPE: str, callable, tuple, or InputFeedbackInitializer DEFAULT: None

topology

Structure of the recurrent weight matrix: a registry name (graph or matrix topology), any matrix-building callable, a (callable, params) tuple, or a configured topology object.

TYPE: str, callable, tuple, or TopologyInitializer DEFAULT: None

recurrent_initializer

First-class alias for topology accepting graph and matrix builders, registered names and custom callables. Supply only one of the two.

TYPE: str, callable, tuple, or TopologyInitializer DEFAULT: None

bias_initializer

Override the default random bias. Uses the same formats as input initialization on a (1, reservoir_size) tensor, then flattens to the bias vector. Requires bias=True. Explicit hook values take precedence over bias_scaling.

TYPE: str, callable, tuple, or InputFeedbackInitializer DEFAULT: None

initial_state_initializer

Initialize a persistent (1, reservoir_size) state template once at construction. Every reset broadcasts an independent copy to each batch item. None keeps the zero-state default. The template moves with .to() and is included in checkpoints.

TYPE: str, callable, tuple, or InputFeedbackInitializer DEFAULT: None

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.

TYPE: device or str DEFAULT: None

dtype

Floating-point initialization precision. Defaults to Torch's default dtype. torch.float64 constructs in double precision rather than rounding float32 weights and converting afterward.

TYPE: dtype DEFAULT: None

seed

Reproducibility seed that deterministically fixes every reservoir parameter — the recurrent (topology) matrix, the feedback and input weights (including the default uniform(-1, 1) draw used when no initializer is given), and the random bias. Accepts a plain int or a torch.Generator, whose initial_seed() defines the master seed without advancing the caller's generator. Independent fixed role seeds drive feedback, input, recurrent weights, bias and reset state. With seed set, a string- or callable-form topology='erdos_renyi' produces the same recurrent matrix on every build, without the ('erdos_renyi', {'seed': ...}) tuple form. An explicit seed inside a tuple/object spec always wins over this argument. When seed=None (the default), one master integer is drawn from Torch's CPU global RNG, then every role uses its own local stream. This advances the global RNG once and remains reproducible under torch.manual_seed. Explicit initializer RNG policies remain owned by their callbacks/objects, including an explicitly bound seed=None.

TYPE: int or Generator DEFAULT: None

ATTRIBUTE DESCRIPTION
weight_feedback

Feedback weight matrix of shape (reservoir_size, feedback_size).

TYPE: Parameter

weight_input

Input weight matrix of shape (reservoir_size, input_size), or None if input_size was not provided.

TYPE: Parameter or None

weight_hh

Dense Parameter or frozen CSR view of the recurrent weight matrix of shape (reservoir_size, reservoir_size).

TYPE: Tensor

bias_h

Bias vector of shape (reservoir_size,), or None if bias=False.

TYPE: Parameter or None

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
def __init__(
    self,
    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 | torch.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: torch.device | str | None = None,
    dtype: torch.dtype | None = None,
) -> None:
    super().__init__()
    if dtype is not None and not dtype.is_floating_point:
        raise TypeError("ESN dtype must be floating point")
    if bias_initializer is not None and not bias:
        raise ValueError("bias_initializer requires bias=True")
    target_device = torch.device(device) if device is not None else torch.get_default_device()
    mps_initialization = target_device.type == "mps"
    if mps_initialization and (dtype or torch.get_default_dtype()) == torch.float64:
        raise ValueError(
            "MPS does not support float64; use dtype=torch.float32 or device='cpu'"
        )
    if mps_initialization and sparse is True:
        raise ValueError("sparse=True is unsupported on MPS; use sparse=False or sparse='auto'")
    # Initialize MPS cells on CPU for consistent behavior across supported
    # Torch versions and matrix factorizations, then move the entire cell.
    # CUDA retains native initialization and device-local generators.
    self._factory_kwargs: dict[str, Any] = {
        "device": "cpu" if mps_initialization else device,
        "dtype": dtype,
    }
    self.bias_initializer = bias_initializer
    self.initial_state_initializer = initial_state_initializer
    # Optional calibration and initial-state buffers leave ordinary ESNs on
    # their original arithmetic path. None buffers do not add checkpoint keys.
    for name in ("_intrinsic_gain", "_intrinsic_bias", "_recurrent_gain", "_initial_state"):
        self.register_buffer(name, None, persistent=True)
    self._intrinsic_gain: torch.Tensor | None
    self._intrinsic_bias: torch.Tensor | None
    self._recurrent_gain: torch.Tensor | None
    self._initial_state: torch.Tensor | None
    # Plain bools avoid optional-buffer __getattr__ lookups in the ordinary
    # (uncalibrated) recurrent hot path.
    self._has_intrinsic = False
    self._has_recurrent_gain = False

    # A sparse-CSR recurrent matmul is only valid for a frozen reservoir;
    # sparse-CSR autograd for this update is fragile, so reject the
    # trainable+sparse combination up front rather than silently degrading.
    if sparse and trainable:
        raise ValueError(
            "sparse=True requires a frozen reservoir (trainable=False): "
            "sparse-CSR autograd for the recurrent update is unsupported. "
            "Use a dense reservoir (sparse=False) for a trainable ESN."
        )

    # leak_rate / noise are validated by their property setters (below), so
    # both the constructor path (``self.leak_rate = ...``) and live writes
    # (``layer.leak_rate = ...``) share one validation.

    # Store configuration
    self.reservoir_size = reservoir_size
    self.feedback_size = feedback_size
    # Treat input_size == 0 the same as input_size is None (no driving
    # input weight matrix is created).  This avoids the historical
    # (reservoir_size, 0) zero-column tensor produced by passing ``0``
    # explicitly from the premade factories.
    self.input_size = input_size if input_size else None
    self.topology = select_recurrent_spec(
        topology=topology, recurrent_initializer=recurrent_initializer
    )
    self.recurrent_initializer = self.topology
    self.spectral_radius = spectral_radius
    self.feedback_initializer = feedback_initializer
    self.input_initializer = input_initializer
    # Backing fields for the leak-rate property.  A scalar leak lives in the
    # float ``_leak_rate``; a per-neuron leak lives in the *persistent*
    # buffer ``_leak_rate_vec`` (so it moves with ``.to()`` / ``.double()``
    # and round-trips through ``state_dict()`` / save-load) and flips
    # ``_is_vector_leak`` so the ``!= 1.0`` scalar fast path is bypassed.
    # Both are pre-seeded here so the property setter — shared by the
    # constructor and live writes — can branch on ``_is_vector_leak`` and
    # reassign the buffer freely (buffers accept reassignment, incl. back to
    # ``None``).
    self._leak_rate: float = 1.0
    self._is_vector_leak: bool = False
    self.register_buffer("_leak_rate_vec", None, persistent=True)
    # ``register_buffer(..., None)`` leaves mypy inferring ``None``; annotate
    # the true buffer type so the vector-leak paths type-check.
    self._leak_rate_vec: torch.Tensor | None
    self.leak_rate = leak_rate
    self.noise = noise
    # ``trainable`` is a live property (see below) whose setter flips
    # ``requires_grad_`` on every parameter.  During ``__init__`` the
    # parameters do not exist yet, so stash the requested value in the
    # backing field directly; the actual ``requires_grad`` freeze is applied
    # after ``_initialize_weights`` (see the block at the end of __init__).
    self._trainable = trainable
    # Frozen sparse weights have canonical component buffers. The
    # nonpersistent CSR tensor is only a zero-copy operator view.
    self._sparse_requested: SparseSpec = sparse
    self._sparse_active: bool = False
    self.register_buffer("_weight_hh_csr", None, persistent=False)
    self._weight_hh_csr: torch.Tensor | None
    self._initialize_compact_buffers()
    self.seed = seed
    # Integer form threaded into the NumPy-backed topology builders and the
    # named feedback/input initializers (they take an int/None seed).  A
    # torch.Generator is reduced to its initial_seed() so the topology stays
    # a pure function of the generator.
    self._seed_int = coerce_seed_to_int(seed)
    if self._seed_int is None:
        # One master draw keeps optional roles independent even without an
        # explicit seed. Device placement never changes which global RNG
        # supplies this master; custom explicit RNG policies still win.
        self._seed_int = int(torch.randint(0, 2**63 - 1, (1,), device="cpu").item())
    # Per-device cache of torch Generators driving the train-mode state
    # noise.  Built lazily on first use (and rebuilt after unpickling — see
    # ``__getstate__``) so the noise stream follows the state's device while
    # staying a deterministic function of ``seed``.  Drawn from a stream
    # *independent* of the weight-init generator so that toggling ``noise``
    # never perturbs weight reproducibility.
    self._noise_generators: dict[torch.device, torch.Generator] = {}

    # Activation function
    self._activation_name = activation
    self.activation_fn = self._get_activation(activation)

    # Store bias config before initialization
    self._bias = bias
    self.bias_scaling = bias_scaling

    # Initialize weight matrices
    self._initialize_weights()
    if self.initial_state_initializer is not None:
        initial = self.weight_feedback.new_empty(1, self.reservoir_size)
        resolved_state = resolve_initializer(
            self.initial_state_initializer,
            seed=_salt_seed(self._seed_int, 4 * _INPUT_SEED_OFFSET),
        )
        assert resolved_state is not None
        resolved_state.initialize(initial)
        if not bool(torch.isfinite(initial).all()):
            raise ValueError("initial_state_initializer must produce finite values")
        self._initial_state = initial

    # Apply the requested trainable state to the freshly-built parameters.
    # Going through the property setter (rather than an inline freeze loop)
    # keeps construction and post-init ``cell.trainable = ...`` writes on a
    # single code path: both flip ``requires_grad_`` on *all* parameters.
    self.trainable = trainable

    # Resolve compact storage once weights and their density are known.
    # Done after the ``trainable`` freeze so the guard sees the final state.
    self._maybe_build_sparse_weight()
    if mps_initialization:
        self.to(device=target_device)

leak_rate property writable

leak_rate: float | Tensor

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.

state_size property

state_size: int

Dimensionality of the hidden state vector.

output_size property

output_size: int

Dimensionality of the per-step output (equals state_size for ESN).

activation property

activation: str

str : Name of the activation function.

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

init_state(batch_size: int, device: device, dtype: dtype) -> Tensor

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
def init_state(
    self,
    batch_size: int,
    device: torch.device,
    dtype: torch.dtype,
) -> torch.Tensor:
    """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.
    """
    if self._initial_state is not None:
        return self._initial_state.to(device=device, dtype=dtype).expand(batch_size, -1).clone()
    return torch.zeros(batch_size, self.state_size, device=device, dtype=dtype)

forward

forward(inputs: list[Tensor], state: Tensor) -> tuple[Tensor, Tensor]

Compute the next ESN state for a single timestep.

PARAMETER DESCRIPTION
inputs

Per-timestep input slices. inputs[0] is the feedback slice of shape (batch, feedback_size). If a driving input is present, inputs[1] has shape (batch, input_size).

TYPE: list[Tensor]

state

Current hidden state of shape (batch, reservoir_size).

TYPE: Tensor

RETURNS DESCRIPTION
output

Next hidden state of shape (batch, reservoir_size).

TYPE: Tensor

new_state

Same tensor as output (state and output are identical for ESN).

TYPE: Tensor

RAISES DESCRIPTION
ValueError

If the feedback feature dimension does not match self.feedback_size, if a driving input is provided but self.weight_input is None, or if the driving input feature dimension does not match self.input_size.

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
def forward(
    self,
    inputs: list[torch.Tensor],
    state: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
    """
    Compute the next ESN state for a single timestep.

    Parameters
    ----------
    inputs : list[torch.Tensor]
        Per-timestep input slices.  `inputs[0]` is the feedback slice
        of shape `(batch, feedback_size)`.  If a driving input is
        present, `inputs[1]` has shape `(batch, input_size)`.
    state : torch.Tensor
        Current hidden state of shape `(batch, reservoir_size)`.

    Returns
    -------
    output : torch.Tensor
        Next hidden state of shape `(batch, reservoir_size)`.
    new_state : torch.Tensor
        Same tensor as output (state and output are identical for ESN).

    Raises
    ------
    ValueError
        If the feedback feature dimension does not match
        `self.feedback_size`, if a driving input is provided but
        `self.weight_input` is `None`, or if the driving input
        feature dimension does not match `self.input_size`.

    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.
    """
    projected = self.project_inputs(inputs)
    pre_activation = projected + self._recurrent(state)
    if self._has_intrinsic:
        assert self._intrinsic_gain is not None and self._intrinsic_bias is not None
        pre_activation = self._intrinsic_gain * pre_activation + self._intrinsic_bias
    new_state = self.activation_fn(pre_activation)
    new_state = self._apply_noise(new_state)
    new_state = self._apply_leak(state, new_state)
    return new_state, new_state

project_inputs

project_inputs(inputs: list[Tensor]) -> Tensor

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; inputs[0] is feedback, inputs[1] (if present) is the driving input.

TYPE: list[Tensor]

RETURNS DESCRIPTION
Tensor

Input projection with the same leading dimensions as the inputs and trailing dimension reservoir_size.

RAISES DESCRIPTION
ValueError

If feature dimensions do not match the cell configuration, or a driving input is supplied to a cell built without input_size.

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
def project_inputs(self, inputs: list[torch.Tensor]) -> torch.Tensor:
    """
    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`).

    Parameters
    ----------
    inputs : list[torch.Tensor]
        Input streams; `inputs[0]` is feedback, `inputs[1]` (if
        present) is the driving input.

    Returns
    -------
    torch.Tensor
        Input projection with the same leading dimensions as the inputs
        and trailing dimension `reservoir_size`.

    Raises
    ------
    ValueError
        If feature dimensions do not match the cell configuration, or a
        driving input is supplied to a cell built without `input_size`.
    """
    fb = inputs[0]

    if fb.shape[-1] != self.feedback_size:
        raise ValueError(
            f"Feedback size mismatch. Expected {self.feedback_size}, got {fb.shape[-1]}"
        )

    projected = F.linear(fb, self.weight_feedback)

    if len(inputs) > 1:
        if self.weight_input is None:
            raise ValueError(
                "Reservoir was initialized without input_size, "
                "but driving input was provided in forward pass"
            )
        x = inputs[1]
        if x.shape[-1] != self.input_size:
            raise ValueError(
                f"Driving input size mismatch. Expected {self.input_size}, got {x.shape[-1]}"
            )
        projected = projected + F.linear(x, self.weight_input)

    if self.bias_h is not None:
        projected = projected + self.bias_h

    return projected

step

step(projected_t: Tensor, state: Tensor) -> tuple[Tensor, Tensor]

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 project_inputs output, shape (batch, reservoir_size).

TYPE: Tensor

state

Current hidden state, shape (batch, reservoir_size).

TYPE: Tensor

RETURNS DESCRIPTION
output

Next hidden state.

TYPE: Tensor

new_state

Same tensor as output.

TYPE: Tensor

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
def step(
    self,
    projected_t: torch.Tensor,
    state: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
    """
    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.

    Parameters
    ----------
    projected_t : torch.Tensor
        Slice of `project_inputs` output, shape
        `(batch, reservoir_size)`.
    state : torch.Tensor
        Current hidden state, shape `(batch, reservoir_size)`.

    Returns
    -------
    output : torch.Tensor
        Next hidden state.
    new_state : torch.Tensor
        Same tensor as output.
    """
    if self._sparse_active or self._has_recurrent_gain:
        # Keep the measured sparse mm-plus-add route.
        # math to the dense branch (``projected_t + state @ weight_hh.T``).
        pre_activation = projected_t + self._recurrent(state)
    else:
        pre_activation = torch.addmm(projected_t, state, self.weight_hh.t())
    if self._has_intrinsic:
        assert self._intrinsic_gain is not None and self._intrinsic_bias is not None
        pre_activation = self._intrinsic_gain * pre_activation + self._intrinsic_bias
    new_state = self.activation_fn(pre_activation)
    new_state = self._apply_noise(new_state)
    new_state = self._apply_leak(state, new_state)
    return new_state, new_state

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

k

Number of delay taps (including the current input). k=1 means only the current input is used (no delay buffer).

TYPE: int DEFAULT: 2

s

Spacing between delay taps, in timesteps.

TYPE: int DEFAULT: 1

p

Polynomial degree for nonlinear feature construction. See cumulative for the two supported degree conventions.

Exact-degree convention (cumulative=False, the default): the nonlinear block contains all unique monomials of exactly degree p from the D = input_dim * k linear features — there are C(D + p - 1, p) of them. Lower-order cross terms (degrees 2, ..., p-1) are not included. For example, NGCell(p=3, include_linear=True) emits constant + linear + cubic with no quadratic terms. This is the historical resdag behaviour and matches Gauthier et al. (arXiv:2106.07688v2), whose Lorenz63 (Eq. 9) and double-scroll (Eq. 10) bases each use a single polynomial degree.

Cumulative-degree convention (cumulative=True): the nonlinear block contains every monomial of degree 2, ..., p (or 1, ..., p when include_linear=False), i.e. the full polynomial basis up to degree p. Many NVAR / NG-RC implementations (and configs ported from them) expect this "degree up to p" basis.

Note.

When p == 1 the degree-1 monomials are the linear features O_lin. To avoid emitting two identical blocks (which makes the readout design matrix rank-deficient), the nonlinear block is omitted whenever p == 1 and include_linear is True. With p == 1 and include_linear=False the degree-1 monomials are kept, since they are then the only delay-embedded features. More generally, whenever include_linear is True the degree-1 monomials are dropped from the nonlinear block (in both conventions), since they would duplicate O_lin; the cumulative basis therefore spans degrees 2, ..., p in that case.

TYPE: int DEFAULT: 2

cumulative

Degree convention for the nonlinear block (see p). False keeps only exact-degree-p monomials (default, unchanged behaviour); True includes all monomials of every degree up to p (the cumulative / "degree up to p" basis).

TYPE: bool DEFAULT: False

include_constant

Whether to prepend a constant 1.0 feature to the output vector. Set True for Lorenz63 forecasting (Eq. 9).

TYPE: bool DEFAULT: True

include_linear

Whether to include the linear delay-embedded features O_lin in the output. Set True for both Lorenz63 and double-scroll (Eq. 9, 10).

TYPE: bool DEFAULT: True

ATTRIBUTE DESCRIPTION
feature_dim

Total dimension of the output feature vector O_total:

D = input_dim * k
# Degrees emitted in the nonlinear block.  Degree 1 is excluded
# whenever include_linear is True (those monomials == O_lin):
d_lo = 2 if include_linear else 1
degrees = range(d_lo, p + 1) if cumulative else [p]
degrees = [g for g in degrees if not (g == 1 and include_linear)]
n_nonlin = sum(C(D + g - 1, g) for g in degrees)
feature_dim = (
    int(include_constant)
    + int(include_linear) * D
    + n_nonlin
)

In the default exact-degree mode (cumulative=False) this reduces to int(include_constant) + int(include_linear) * D + C(D + p - 1, p), with the C(...) term dropped only in the p == 1 / include_linear=True duplicate-column case.

TYPE: int

state_size

Number of rows in the delay buffer: (k - 1) * s. When k=1 this is 0 and the buffer is empty.

TYPE: int

monomial_indices

Long tensor of shape (n_monomials, p) containing the column indices into O_lin for each monomial. Registered as a buffer. Each row lists the O_lin columns multiplied together to form one monomial. In exact-degree mode every row has p distinct index slots; in cumulative mode lower-degree monomials are right-padded with -1 sentinels (gathered from a prepended 1.0 column at runtime) so all rows share the same width p.

TYPE: Tensor

delay_indices

Long tensor of shape (k-1,) containing the row indices into the delay buffer for extracting the delay taps. Registered as a buffer.

TYPE: Tensor

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
def __init__(
    self,
    input_dim: int,
    k: int = 2,
    s: int = 1,
    p: int = 2,
    cumulative: bool = False,
    include_constant: bool = True,
    include_linear: bool = True,
) -> None:
    super().__init__()
    # NG-RC has no floating-point weights. An empty buffer records .to()
    # device/dtype choices for reset_state(batch_size=...) and state restore.
    self.register_buffer("_device_dtype_anchor", torch.empty(0), persistent=False)

    if k < 1:
        raise ValueError(f"k must be >= 1, got {k}")
    if s < 1:
        raise ValueError(f"s must be >= 1, got {s}")
    if p < 1:
        raise ValueError(f"p must be >= 1, got {p}")

    self.input_dim = input_dim
    self.k = k
    self.s = s
    self.p = p
    self.cumulative = cumulative
    self.include_constant = include_constant
    self.include_linear = include_linear

    # D = total linear feature dimension
    linear_feature_dim = input_dim * k

    # Precompute delay-tap row indices into the buffer (shape: (k-1,)).
    # For j = 1, ..., k-1:  X_{i - j*s} lives at row (k-1-j)*s of the
    # buffer (which holds inputs chronologically oldest-first).
    if k > 1:
        delay_idx = torch.tensor([(k - 1 - j) * s for j in range(1, k)], dtype=torch.long)
    else:
        delay_idx = torch.zeros(0, dtype=torch.long)
    self.register_buffer("delay_indices", delay_idx)

    # ------------------------------------------------------------------
    # Decide which monomial degrees the nonlinear block emits.
    #
    # Exact-degree mode (cumulative=False): only degree p.
    # Cumulative mode (cumulative=True):    every degree 1..p.
    #
    # When include_linear is True the degree-1 monomials are exactly the
    # columns of O_lin, so emitting them again would duplicate every linear
    # column and make the readout design matrix rank-deficient.  Drop
    # degree 1 from the nonlinear block in that case (this generalises the
    # historical p==1 special case to both conventions).
    # ------------------------------------------------------------------
    degrees = range(1, p + 1) if cumulative else range(p, p + 1)
    emit_degrees = [g for g in degrees if not (g == 1 and include_linear)]

    # Build the monomial index rows.  Exact-degree mode keeps the historical
    # tight (n_monomials, p) layout with no padding.  Cumulative mode mixes
    # degrees, so every row is right-padded to width p with the -1 sentinel,
    # which is gathered from a prepended 1.0 column (the multiplicative
    # identity) at runtime — keeping a single vectorised gather/prod.
    raw_indices: list[tuple[int, ...]] = []
    for g in emit_degrees:
        raw_indices.extend(
            itertools.combinations_with_replacement(range(linear_feature_dim), g)
        )

    self._pad_with_ones: bool = cumulative and len(emit_degrees) > 1
    if self._pad_with_ones:
        # Right-pad short monomials with the -1 ones-sentinel to width p.
        padded = [list(idx) + [-1] * (p - len(idx)) for idx in raw_indices]
        monomial_idx = (
            torch.tensor(padded, dtype=torch.long)
            if padded
            else torch.zeros(0, p, dtype=torch.long)
        )
    else:
        # Tight layout: every monomial already has exactly ``width`` factors.
        width = emit_degrees[0] if emit_degrees else p
        monomial_idx = (
            torch.tensor([list(idx) for idx in raw_indices], dtype=torch.long)
            if raw_indices
            else torch.zeros(0, width, dtype=torch.long)
        )
    self.register_buffer("monomial_indices", monomial_idx)

    n_monomials = len(raw_indices)

    # The nonlinear block is omitted entirely only when no degrees survive
    # the degree-1 filter (i.e. p == 1 and include_linear is True).
    self._emit_nonlinear: bool = len(emit_degrees) > 0

    # Total output dimension
    self._feature_dim: int = (
        int(include_constant)
        + int(include_linear) * linear_feature_dim
        + int(self._emit_nonlinear) * n_monomials
    )

    if self._feature_dim > 10_000:
        warnings.warn(
            f"NGCell: feature_dim={self._feature_dim} exceeds 10,000. "
            f"Consider reducing k, p, or input_dim to avoid combinatorial explosion. "
            f"(linear_feature_dim={linear_feature_dim}, n_monomials={n_monomials})",
            stacklevel=2,
        )

feature_dim property

feature_dim: int

Total dimension of the O_total output vector.

output_size property

output_size: int

Dimensionality of the per-step output (equals feature_dim).

state_size property

state_size: int

Number of rows in the delay buffer: (k-1)*s.

init_state

init_state(batch_size: int, device: device | str, dtype: dtype) -> Tensor

Return a zero-filled initial delay buffer.

PARAMETER DESCRIPTION
batch_size

Number of samples in the batch.

TYPE: int

device

Target device for the buffer.

TYPE: device or str

dtype

Target dtype for the buffer.

TYPE: dtype

RETURNS DESCRIPTION
Tensor

Zero tensor of shape (batch_size, state_size, input_dim). When k=1 the second dimension is 0 (empty buffer).

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
def init_state(
    self,
    batch_size: int,
    device: torch.device | str,
    dtype: torch.dtype,
) -> torch.Tensor:
    """
    Return a zero-filled initial delay buffer.

    Parameters
    ----------
    batch_size : int
        Number of samples in the batch.
    device : torch.device or str
        Target device for the buffer.
    dtype : torch.dtype
        Target dtype for the buffer.

    Returns
    -------
    torch.Tensor
        Zero tensor of shape `(batch_size, state_size, input_dim)`.
        When `k=1` the second dimension is 0 (empty buffer).
    """
    return torch.zeros(batch_size, self.state_size, self.input_dim, device=device, dtype=dtype)

forward

forward(inputs: list[Tensor], state: Tensor) -> tuple[Tensor, Tensor]

Compute the NG-RC feature vector for a single timestep.

PARAMETER DESCRIPTION
inputs

Per-timestep input slices. inputs[0] is the current input of shape (batch, input_dim). NG-RC has no driving inputs, so only inputs[0] is consumed (the wrapping resdag.layers.reservoirs.ngrc.NGReservoirLayer rejects driving inputs before they reach the cell).

TYPE: list[Tensor]

state

Delay buffer of shape (batch, state_size, input_dim).

TYPE: Tensor

RETURNS DESCRIPTION
features

Output feature vector O_total of shape (batch, feature_dim).

TYPE: Tensor

new_state

Updated delay buffer of shape (batch, state_size, input_dim).

TYPE: Tensor

RAISES DESCRIPTION
ValueError

If inputs[0]'s trailing (feature) dimension does not equal input_dim.

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
def forward(
    self,
    inputs: list[torch.Tensor],
    state: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
    """
    Compute the NG-RC feature vector for a single timestep.

    Parameters
    ----------
    inputs : list[torch.Tensor]
        Per-timestep input slices.  `inputs[0]` is the current input
        of shape `(batch, input_dim)`.  NG-RC has no driving inputs, so
        only `inputs[0]` is consumed (the wrapping
        `resdag.layers.reservoirs.ngrc.NGReservoirLayer` rejects driving
        inputs before they reach the cell).
    state : torch.Tensor
        Delay buffer of shape `(batch, state_size, input_dim)`.

    Returns
    -------
    features : torch.Tensor
        Output feature vector `O_total` of shape
        `(batch, feature_dim)`.
    new_state : torch.Tensor
        Updated delay buffer of shape `(batch, state_size, input_dim)`.

    Raises
    ------
    ValueError
        If `inputs[0]`'s trailing (feature) dimension does not equal
        `input_dim`.
    """
    x = inputs[0]
    self._check_input_dim(x)
    batch = x.shape[0]

    # ------------------------------------------------------------------
    # 1. Build O_lin (linear delay-embedded features, Eq. 5)
    # ------------------------------------------------------------------
    if self.k > 1:
        # Extract (k-1) delay taps from the buffer *before* update.
        # delay_indices selects rows so that taps[:,0,:] = X_{i-s},
        # taps[:,1,:] = X_{i-2s}, ..., taps[:,k-2,:] = X_{i-(k-1)s}.
        delay_indices = cast(torch.Tensor, self.delay_indices)
        taps = state[:, delay_indices, :]  # (batch, k-1, input_dim)
        # O_lin = [X_i || X_{i-s} || ... || X_{i-(k-1)s}]
        o_lin = torch.cat([x.unsqueeze(1), taps], dim=1).reshape(batch, self.k * self.input_dim)
    else:
        # k=1: no delay taps, just current input
        o_lin = x  # (batch, input_dim)

    # ------------------------------------------------------------------
    # 2. Update delay buffer (FIFO: drop oldest row, append current x)
    # ------------------------------------------------------------------
    if self.state_size > 0:
        # Keep the last state_size rows after appending x.
        new_state = torch.cat([state, x.unsqueeze(1)], dim=1)[:, -self.state_size :, :]
    else:
        new_state = state  # empty tensor, no change

    # ------------------------------------------------------------------
    # 3. Nonlinear features (Eq. 6): polynomial monomials from O_lin.
    #
    # Exact-degree mode emits only degree-p monomials; cumulative mode emits
    # every degree up to p.  The gather/product is delegated to
    # :meth:`_build_nonlinear`, which handles the padded cumulative layout.
    # The block is omitted only when p == 1 and include_linear is True
    # (the degree-1 monomials are then exactly the columns of O_lin).
    # ------------------------------------------------------------------
    # ------------------------------------------------------------------
    # 4. Assemble O_total = [c] ⊕ O_lin ⊕ O_nonlin (Eq. 9 / Eq. 10)
    # ------------------------------------------------------------------
    parts: list[torch.Tensor] = []
    if self.include_constant:
        parts.append(torch.ones(batch, 1, device=x.device, dtype=x.dtype))
    if self.include_linear:
        parts.append(o_lin)
    if self._emit_nonlinear:
        parts.append(self._build_nonlinear(o_lin))  # (batch, n_monomials)

    o_total = torch.cat(parts, dim=-1)  # (batch, feature_dim)

    return o_total, new_state

forward_sequence

forward_sequence(x: Tensor, state: Tensor) -> tuple[Tensor, Tensor]

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 (batch, timesteps, input_dim).

TYPE: Tensor

state

Incoming delay buffer of shape (batch, state_size, input_dim), chronologically oldest-first. This holds the (k-1)*s inputs immediately preceding x[:, 0] and supplies the delay taps for the first timesteps (zeros for a cold start).

TYPE: Tensor

RETURNS DESCRIPTION
features

Output features O_total of shape (batch, timesteps, feature_dim).

TYPE: Tensor

new_state

Updated delay buffer of shape (batch, state_size, input_dim), holding the last state_size inputs of x (or, when the sequence is shorter than the buffer, carried-over history), so a subsequent streaming forward continues seamlessly.

TYPE: Tensor

RAISES DESCRIPTION
ValueError

If x's trailing (feature) dimension does not equal input_dim.

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
def forward_sequence(
    self,
    x: torch.Tensor,
    state: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
    """
    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.

    Parameters
    ----------
    x : torch.Tensor
        Input sequence of shape `(batch, timesteps, input_dim)`.
    state : torch.Tensor
        Incoming delay buffer of shape `(batch, state_size, input_dim)`,
        chronologically oldest-first.  This holds the `(k-1)*s` inputs
        immediately preceding `x[:, 0]` and supplies the delay taps for
        the first timesteps (zeros for a cold start).

    Returns
    -------
    features : torch.Tensor
        Output features `O_total` of shape
        `(batch, timesteps, feature_dim)`.
    new_state : torch.Tensor
        Updated delay buffer of shape `(batch, state_size, input_dim)`,
        holding the last `state_size` inputs of `x` (or, when the
        sequence is shorter than the buffer, carried-over history), so a
        subsequent streaming `forward` continues seamlessly.

    Raises
    ------
    ValueError
        If `x`'s trailing (feature) dimension does not equal
        `input_dim`.

    See Also
    --------
    NGCell.forward : Single-step counterpart driving the streaming path.
    """
    self._check_input_dim(x)
    batch, seq_len, _ = x.shape
    pad = self.state_size  # == (k - 1) * s

    # ------------------------------------------------------------------
    # 1. Build O_lin for the whole sequence (Eq. 5).
    #
    # Prepend the incoming delay buffer (oldest-first) so the first
    # timesteps draw their delay taps from carried-over history; a cold
    # start contributes zeros, matching the per-step loop's empty buffer.
    # For delay tap j (0..k-1), X_{i-j*s} at output index i lives at
    # padded[:, pad + i - j*s, :], i.e. the length-T window starting at
    # column (pad - j*s).
    # ------------------------------------------------------------------
    if self.k > 1:
        padded = torch.cat([state, x], dim=1)  # (batch, pad + T, input_dim)
        taps = [
            padded[:, pad - j * self.s : pad - j * self.s + seq_len, :] for j in range(self.k)
        ]
        o_lin = torch.cat(taps, dim=-1)  # (batch, T, k * input_dim)
    else:
        # k=1: no delay taps, O_lin is just the current input.
        o_lin = x  # (batch, T, input_dim)

    # ------------------------------------------------------------------
    # 2. Updated delay buffer: the last ``pad`` rows of the padded stream
    #    (FIFO drop-oldest / append-current applied to the full sequence).
    # ------------------------------------------------------------------
    if pad > 0:
        new_state = torch.cat([state, x], dim=1)[:, -pad:, :]
    else:
        new_state = state  # empty buffer, unchanged

    # ------------------------------------------------------------------
    # 3. Assemble O_total = [c] + O_lin + O_nonlin (Eq. 9 / Eq. 10).
    #    The constant-ones block is allocated once for the whole sequence;
    #    monomials are gathered over the full (batch, T, *) tensor in one op.
    # ------------------------------------------------------------------
    parts: list[torch.Tensor] = []
    if self.include_constant:
        parts.append(torch.ones(batch, seq_len, 1, device=x.device, dtype=x.dtype))
    if self.include_linear:
        parts.append(o_lin)
    if self._emit_nonlinear:
        parts.append(self._build_nonlinear(o_lin))  # (batch, T, n_monomials)

    o_total = torch.cat(parts, dim=-1)  # (batch, T, feature_dim)

    return o_total, new_state

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 (batch, state_size, input_dim).

TYPE: Tensor

RAISES DESCRIPTION
ValueError

If state is not 3-D or its non-batch dimensions do not match (state_size, input_dim).

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
def validate_state(self, state: torch.Tensor) -> None:
    """
    Validate the 3-D delay-buffer layout used by NG-RC.

    Parameters
    ----------
    state : torch.Tensor
        Candidate state of shape `(batch, state_size, input_dim)`.

    Raises
    ------
    ValueError
        If `state` is not 3-D or its non-batch dimensions do not match
        `(state_size, input_dim)`.
    """
    expected = (self.state_size, self.input_dim)
    if state.dim() != 3 or state.shape[1:] != torch.Size(expected):
        raise ValueError(
            f"NGCell.validate_state: expected a 3-D delay buffer of shape "
            f"(batch, {self.state_size}, {self.input_dim}); "
            f"got tensor of shape {tuple(state.shape)}."
        )

ES2NCell

ES2NCell(reservoir_size: int, feedback_size: int, beta: float = 0.9, **kwargs: object)

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
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
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
>>> 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
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
def __init__(
    self,
    reservoir_size: int,
    feedback_size: int,
    beta: float = 0.9,
    **kwargs: object,
) -> None:
    # ``beta`` is validated by its property setter (shared by the constructor
    # and live writes).  It is stored *before* super().__init__ so the setter
    # has its backing field ready, then re-validated below once the object is
    # fully initialised.
    self._beta: float = 0.9
    super().__init__(reservoir_size=reservoir_size, feedback_size=feedback_size, **kwargs)  # type: ignore[arg-type]
    self.beta = beta

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
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
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
>>> 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
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
def __init__(
    self,
    reservoir_size: int,
    feedback_size: int,
    alpha: float = 0.5,
    beta: float = 0.9,
    **kwargs: object,
) -> None:
    # Backing fields seeded before super().__init__ so the property setters
    # (shared by construction and live writes) have targets; re-assigned
    # below once the object is fully initialised.
    self._alpha: float = 0.5
    self._beta: float = 0.9
    super().__init__(reservoir_size=reservoir_size, feedback_size=feedback_size, **kwargs)  # type: ignore[arg-type]
    self.alpha = alpha
    self.beta = beta

alpha property writable

alpha: float

float : Scaling of the orthogonal skip (residual) branch.

A live knob: assigning to it (directly or through ResESNLayer.alpha = ...) validates the value and takes effect on the next forward.

beta property writable

beta: float

float : Scaling of the nonlinear branch.

A live knob: assigning to it (directly or through ResESNLayer.beta = ...) validates the value and takes effect on the next forward.

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

\[ \begin{aligned} z_t &= \sigma(W_{iz}\,u_t + W_{hz}\,h_{t-1} + b_z), \\ \tilde{h}_t &= \phi(W_{ih}\,u_t + W_{hh}\,h_{t-1} + b_h), \\ h_t &= z_t \odot h_{t-1} + (1 - z_t) \odot \tilde{h}_t, \end{aligned} \]

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 (default 2.0) biases the update gate toward retention: b_z = update_gate_bias makes z start 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_radius scales 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 hidden_size).

TYPE: int

feedback_size

Dimension of the feedback signal. Required.

TYPE: int

input_size

Dimension of an optional driving input. If None (or 0), no driving-input weights are created.

TYPE: int DEFAULT: None

spectral_radius

Target spectral radius for the recurrent candidate weight \(W_{hh}\). If None, no scaling is applied.

TYPE: float DEFAULT: None

bias

Whether to include gate biases (b_z, b_h).

TYPE: bool DEFAULT: True

bias_scaling

Scale of the random candidate bias b_h: entries are drawn from uniform(-bias_scaling, bias_scaling). The update-gate bias b_z is set to the constant update_gate_bias (retention bias), not randomised. Ignored when bias=False (both biases are then None and the update gate starts centred at z ≈ 0.5).

TYPE: float DEFAULT: 1.0

update_gate_bias

Constant added to the update-gate pre-activation (the value of b_z when bias=True). A positive value biases z toward 1 (retention). 2.0 gives z ≈ 0.88 at init. Set 0.0 for an unbiased update gate.

TYPE: float DEFAULT: 2.0

activation

Candidate nonlinearity \(\phi\). "relu" is the LiGRU default; "tanh" recovers a classical-GRU-like bounded candidate.

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

gate_activation

Update-gate nonlinearity \(\sigma\). "sigmoid" (the gate convention) keeps z in (0, 1); other names are accepted for experimentation but only "sigmoid" guarantees a valid gate.

TYPE: (sigmoid, ...) DEFAULT: 'sigmoid'

trainable

If True, all weights participate in backpropagation. Frozen ESN-style reservoirs use False; gated reservoirs are often best True.

TYPE: bool DEFAULT: False

feedback_initializer

Initializer for the feedback weight matrix (drive path). Same accepted forms as ESNCell.

TYPE: str, callable, tuple, or InputFeedbackInitializer DEFAULT: None

input_initializer

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

TYPE: str, callable, tuple, or InputFeedbackInitializer DEFAULT: None

topology

Structure of the recurrent candidate weight \(W_{hh}\). The recurrent gate weights W_hz are always dense-random (a graph topology would make the update gate structurally sparse, which is not the intent).

TYPE: str, callable, tuple, or TopologyInitializer DEFAULT: None

seed

Reproducibility seed for independent weight, bias and reset-state roles. Integers and a generator's initial_seed() do not advance the caller's RNG. None draws one master seed from Torch's CPU global RNG. Explicit initializer seeds and callback-owned generators retain their own policy.

TYPE: int or Generator DEFAULT: None

recurrent_initializer

First-class alias for topology. Supply one spelling only. Names, tuples, callables and registered initializer objects are accepted.

TYPE: spec DEFAULT: None

bias_initializer

Input/feedback initializer grammar applied to a (1, reservoir_size) view of the bias. Requires bias=True; overrides bias_scaling.

TYPE: spec DEFAULT: None

initial_state_initializer

Initializes a persistent (1, cell.state_size) reset template once. Each batch example receives an independent copy at reset. Zero by default.

TYPE: spec DEFAULT: None

device

Initial parameter location. Metal construction initializes on CPU before transferring to support initialization operations across backends.

TYPE: device or str DEFAULT: None

dtype

Floating precision used during initialization, not only after conversion.

TYPE: dtype DEFAULT: None

gate_recurrent_initializer

Separate recurrent gate matrix. Defaults to small dense random weights.

TYPE: spec DEFAULT: None

gate_spectral_radius

Outer radius target for the gate recurrence, respecting its scaling policy.

TYPE: float DEFAULT: None

gate_feedback_initializer

Separate gate projections. Omitted projections share candidate weights. A driver gate initializer requires input_size.

TYPE: spec DEFAULT: None

gate_input_initializer

Separate gate projections. Omitted projections share candidate weights. A driver gate initializer requires input_size.

TYPE: spec DEFAULT: None

gate_bias_initializer

Gate-bias initializer on (1, reservoir_size); overrides update_gate_bias. Requires bias=True.

TYPE: spec DEFAULT: None

ATTRIBUTE DESCRIPTION
weight_feedback

Feedback drive weight W_fb of shape (reservoir_size, feedback_size).

TYPE: Parameter

weight_input

Driving-input drive weight W_in of shape (reservoir_size, input_size), or None.

TYPE: Parameter or None

weight_hh

Recurrent candidate weight \(W_{hh}\) of shape (reservoir_size, reservoir_size) (spectral-radius scaled).

TYPE: Parameter

weight_hz

Recurrent update-gate weight \(W_{hz}\) of shape (reservoir_size, reservoir_size).

TYPE: Parameter

bias_h

Candidate bias b_h, shape (reservoir_size,), or None.

TYPE: Parameter or None

bias_z

Update-gate bias b_z (initialised to update_gate_bias), shape (reservoir_size,), or None.

TYPE: Parameter or None

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
def __init__(
    self,
    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: torch.device | str | None = None,
    dtype: torch.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,
) -> None:
    super().__init__()

    self.reservoir_size = reservoir_size
    self.feedback_size = feedback_size
    # Treat input_size == 0 the same as None (no driving-input weights),
    # matching ESNCell and the ott_esn/power_augmented factories.
    self.input_size = input_size if input_size else None
    self.topology = select_recurrent_spec(
        topology=topology, recurrent_initializer=recurrent_initializer
    )
    if dtype is not None and not dtype.is_floating_point:
        raise ValueError("Reservoir dtype must be floating point")
    if not bias and bias_initializer is not None:
        raise ValueError("bias_initializer requires bias=True")
    self.bias_initializer = bias_initializer
    self.initial_state_initializer = initial_state_initializer
    target_device = torch.device(device) if device is not None else torch.empty(0).device
    if target_device.type == "mps" and (dtype or torch.get_default_dtype()) == torch.float64:
        raise TypeError("MPS does not support float64; use float32 or CPU")
    # Initialize on CPU before a Metal transfer for portable RNG/linalg support.
    init_device = "cpu" if target_device is not None and target_device.type == "mps" else device
    self._factory_kwargs: dict[str, Any] = {"device": init_device, "dtype": dtype}
    if not bias and gate_bias_initializer is not None:
        raise ValueError("gate_bias_initializer requires bias=True")
    if not self.input_size and gate_input_initializer is not None:
        raise ValueError("gate_input_initializer requires input_size")
    if gate_spectral_radius is not None and (
        not torch.isfinite(torch.tensor(gate_spectral_radius)) or gate_spectral_radius < 0
    ):
        raise ValueError("gate_spectral_radius must be finite and non-negative")
    self.gate_recurrent_initializer = gate_recurrent_initializer
    self.gate_feedback_initializer = gate_feedback_initializer
    self.gate_input_initializer = gate_input_initializer
    self.gate_bias_initializer = gate_bias_initializer
    self.gate_spectral_radius = gate_spectral_radius
    self._separate_gate_drive = (
        gate_feedback_initializer is not None or gate_input_initializer is not None
    )
    self.spectral_radius = spectral_radius
    self.feedback_initializer = feedback_initializer
    self.input_initializer = input_initializer
    self.update_gate_bias = float(update_gate_bias)

    self._trainable = trainable
    self.seed = seed
    self._seed_int = coerce_seed_to_int(seed)
    if self._seed_int is None:
        self._seed_int = int(torch.randint(0, 2**63 - 1, (1,), device="cpu").item())

    self._activation_name = activation
    self.activation_fn = self._get_activation(activation)
    self._gate_activation_name = gate_activation
    self.gate_activation_fn = self._get_activation(gate_activation)

    self._bias = bias
    self.bias_scaling = bias_scaling

    self._initialize_weights()
    install_initial_state(
        self,
        self.initial_state_initializer,
        seed=_salt_seed(self._seed_int, 0x9E3779B9 * 7),
        state_size=self.state_size,
        reference=self.weight_feedback,
    )

    # Apply the requested freeze through the base property so construction
    # and post-init ``cell.trainable = ...`` share one code path.
    self.trainable = trainable
    if target_device is not None and target_device.type == "mps":
        self.to(target_device)

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

hidden_size property

hidden_size: int

Width of a single packed state tensor (== reservoir_size).

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

output_size property

output_size: int

Dimensionality of the per-step output (the hidden state h).

activation property

activation: str

str : Name of the candidate activation function \(\phi\).

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

init_state(batch_size: int, device: device, dtype: dtype) -> Tensor

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
def init_state(
    self,
    batch_size: int,
    device: torch.device,
    dtype: torch.dtype,
) -> torch.Tensor:
    """Return a zero packed state of shape `(batch_size, state_size)`."""
    return initialized_state(
        self,
        batch_size,
        self.state_size,
        device,
        dtype,
    )

forward

forward(inputs: list[Tensor], state: Tensor) -> tuple[Tensor, Tensor]

Compute the next gated state for a single timestep.

PARAMETER DESCRIPTION
inputs

inputs[0] is the feedback slice (batch, feedback_size); inputs[1] (if present) is the driving input (batch, input_size).

TYPE: list[Tensor]

state

Current packed state of shape (batch, state_size).

TYPE: Tensor

RETURNS DESCRIPTION
output

Next hidden state h of shape (batch, reservoir_size).

TYPE: Tensor

new_state

Next packed state (identical to output for this single-state cell).

TYPE: Tensor

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
def forward(
    self,
    inputs: list[torch.Tensor],
    state: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
    """
    Compute the next gated state for a single timestep.

    Parameters
    ----------
    inputs : list[torch.Tensor]
        `inputs[0]` is the feedback slice `(batch, feedback_size)`;
        `inputs[1]` (if present) is the driving input
        `(batch, input_size)`.
    state : torch.Tensor
        Current packed state of shape `(batch, state_size)`.

    Returns
    -------
    output : torch.Tensor
        Next hidden state `h` of shape `(batch, reservoir_size)`.
    new_state : torch.Tensor
        Next packed state (identical to `output` for this single-state cell).
    """
    drive = self.project_inputs(inputs)
    return self.step(drive, state)

project_inputs

project_inputs(inputs: list[Tensor]) -> Tensor

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

inputs[0] feedback, inputs[1] (optional) driving input.

TYPE: list[Tensor]

RETURNS DESCRIPTION
Tensor

Drive u with the inputs' leading dims and trailing dimension reservoir_size.

RAISES DESCRIPTION
ValueError

On a feedback/driving-input feature-dimension mismatch, or if a driving input is supplied to a cell built without input_size.

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
def project_inputs(self, inputs: list[torch.Tensor]) -> torch.Tensor:
    """
    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`).

    Parameters
    ----------
    inputs : list[torch.Tensor]
        `inputs[0]` feedback, `inputs[1]` (optional) driving input.

    Returns
    -------
    torch.Tensor
        Drive `u` with the inputs' leading dims and trailing dimension
        `reservoir_size`.

    Raises
    ------
    ValueError
        On a feedback/driving-input feature-dimension mismatch, or if a
        driving input is supplied to a cell built without `input_size`.
    """
    fb = inputs[0]
    if fb.shape[-1] != self.feedback_size:
        raise ValueError(
            f"Feedback size mismatch. Expected {self.feedback_size}, got {fb.shape[-1]}"
        )
    drive = F.linear(fb, self.weight_feedback)

    if len(inputs) > 1:
        if self.weight_input is None:
            raise ValueError(
                "Reservoir was initialized without input_size, "
                "but driving input was provided in forward pass"
            )
        x = inputs[1]
        if x.shape[-1] != self.input_size:
            raise ValueError(
                f"Driving input size mismatch. Expected {self.input_size}, got {x.shape[-1]}"
            )
        drive = drive + F.linear(x, self.weight_input)

    if self._separate_gate_drive:
        gate_feedback = (
            self.weight_gate_feedback
            if self.weight_gate_feedback is not None
            else self.weight_feedback
        )
        gate_drive = F.linear(fb, gate_feedback)
        if len(inputs) > 1:
            gate_input = (
                self.weight_gate_input
                if self.weight_gate_input is not None
                else self.weight_input
            )
            assert gate_input is not None
            gate_drive = gate_drive + F.linear(inputs[1], gate_input)
        return torch.cat((drive, gate_drive), dim=-1)
    return drive

step

step(projected_t: Tensor, state: Tensor) -> tuple[Tensor, Tensor]

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 u_t of shape (batch, reservoir_size).

TYPE: Tensor

state

Current packed state (batch, state_size).

TYPE: Tensor

RETURNS DESCRIPTION
output

Next hidden state h of shape (batch, reservoir_size).

TYPE: Tensor

new_state

Next packed state (identical to output here).

TYPE: Tensor

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
def step(
    self,
    projected_t: torch.Tensor,
    state: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
    """
    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.

    Parameters
    ----------
    projected_t : torch.Tensor
        Per-timestep drive `u_t` of shape `(batch, reservoir_size)`.
    state : torch.Tensor
        Current packed state `(batch, state_size)`.

    Returns
    -------
    output : torch.Tensor
        Next hidden state `h` of shape `(batch, reservoir_size)`.
    new_state : torch.Tensor
        Next packed state (identical to `output` here).
    """
    (h,) = _split_state(state, self.reservoir_size)
    if self._separate_gate_drive:
        candidate_drive, gate_drive = projected_t.split(self.reservoir_size, dim=-1)
    else:
        candidate_drive = gate_drive = projected_t

    # Update-gate pre-activation: drive + recurrent gate term + retention bias.
    z_pre = gate_drive + F.linear(h, self.weight_hz)
    if self.bias_z is not None:
        z_pre = z_pre + self.bias_z
    z = self.gate_activation_fn(z_pre)

    # Candidate pre-activation: drive + recurrent candidate term + bias.
    h_pre = candidate_drive + F.linear(h, self.weight_hh)
    if self.bias_h is not None:
        h_pre = h_pre + self.bias_h
    h_tilde = self.activation_fn(h_pre)

    # Retention convention: z→1 keeps h, z→0 writes the candidate.
    new_h = z * h + (1.0 - z) * h_tilde
    new_state = _pack_state(new_h)
    return new_h, new_state

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
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
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
`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
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
def __init__(
    self,
    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-6,
    atol: float = 1e-8,
    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: torch.device | str | None = None,
    dtype: torch.dtype | None = None,
) -> None:
    if substeps < 1:
        raise ValueError(f"substeps must be a positive integer, got {substeps}")
    if solver not in _VALID_SOLVERS:
        raise ValueError(f"Unknown solver {solver!r}. Supported: {sorted(_VALID_SOLVERS)}.")
    self.dt = float(dt)
    self.substeps = int(substeps)
    self.solver = solver
    self.torchdiffeq_method = torchdiffeq_method
    self.rtol = float(rtol)
    self.atol = float(atol)

    # ESNCell owns the recurrent / feedback / input / bias machinery; drive
    # it with a fixed leak_rate=1.0 (the integrator replaces leaky mixing) and
    # no state noise (not part of the continuous-cell formulation).
    super().__init__(
        reservoir_size=reservoir_size,
        feedback_size=feedback_size,
        input_size=input_size,
        spectral_radius=spectral_radius,
        bias=bias,
        bias_scaling=bias_scaling,
        activation=activation,
        leak_rate=1.0,
        noise=0.0,
        trainable=trainable,
        feedback_initializer=feedback_initializer,
        input_initializer=input_initializer,
        topology=topology,
        seed=seed,
        recurrent_initializer=recurrent_initializer,
        bias_initializer=bias_initializer,
        initial_state_initializer=initial_state_initializer,
        device=device,
        dtype=dtype,
    )

dt property writable

dt: float

Positive, finite integration interval; changes apply to the next step.

vector_field abstractmethod

vector_field(state: Tensor, projected_u: Tensor) -> Tensor

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 (batch, reservoir_size).

TYPE: Tensor

projected_u

Precomputed input drive for this interval, shape (batch, reservoir_size), constant across sub-steps.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The time derivative \(\dot h\), shape (batch, reservoir_size).

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
@abstractmethod
def vector_field(self, state: torch.Tensor, projected_u: torch.Tensor) -> torch.Tensor:
    r"""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`.

    Parameters
    ----------
    state : torch.Tensor
        Current reservoir state, shape `(batch, reservoir_size)`.
    projected_u : torch.Tensor
        Precomputed input drive for this interval, shape
        `(batch, reservoir_size)`, constant across sub-steps.

    Returns
    -------
    torch.Tensor
        The time derivative $\dot h$, shape `(batch, reservoir_size)`.
    """
    ...

output_from_state

output_from_state(state: Tensor) -> Tensor

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 (batch, reservoir_size).

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Per-step output, shape (batch, output_size).

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
def output_from_state(self, state: torch.Tensor) -> torch.Tensor:
    """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.

    Parameters
    ----------
    state : torch.Tensor
        Integrated reservoir state, shape `(batch, reservoir_size)`.

    Returns
    -------
    torch.Tensor
        Per-step output, shape `(batch, output_size)`.
    """
    return state

forward

forward(inputs: list[Tensor], state: Tensor) -> tuple[Tensor, Tensor]

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

inputs[0] is the feedback slice (batch, feedback_size); inputs[1] (optional) the driving input (batch, input_size).

TYPE: list[Tensor]

state

Current reservoir state, shape (batch, reservoir_size).

TYPE: Tensor

RETURNS DESCRIPTION
output

Per-step output (batch, output_size) from output_from_state.

TYPE: Tensor

new_state

Integrated reservoir state (batch, reservoir_size).

TYPE: Tensor

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
def forward(
    self,
    inputs: list[torch.Tensor],
    state: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
    r"""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`.

    Parameters
    ----------
    inputs : list[torch.Tensor]
        `inputs[0]` is the feedback slice `(batch, feedback_size)`;
        `inputs[1]` (optional) the driving input `(batch, input_size)`.
    state : torch.Tensor
        Current reservoir state, shape `(batch, reservoir_size)`.

    Returns
    -------
    output : torch.Tensor
        Per-step output `(batch, output_size)` from
        `output_from_state`.
    new_state : torch.Tensor
        Integrated reservoir state `(batch, reservoir_size)`.
    """
    projected = self.project_inputs(inputs)
    return self.step(projected, state)

step

step(projected_t: Tensor, state: Tensor) -> tuple[Tensor, Tensor]

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 ESNCell.project_inputs, shape (batch, reservoir_size).

TYPE: Tensor

state

Current reservoir state, shape (batch, reservoir_size).

TYPE: Tensor

RETURNS DESCRIPTION
output

Per-step output (batch, output_size).

TYPE: Tensor

new_state

Integrated reservoir state (batch, reservoir_size).

TYPE: Tensor

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
def step(
    self,
    projected_t: torch.Tensor,
    state: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
    r"""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.

    Parameters
    ----------
    projected_t : torch.Tensor
        Slice of `ESNCell.project_inputs`, shape
        `(batch, reservoir_size)`.
    state : torch.Tensor
        Current reservoir state, shape `(batch, reservoir_size)`.

    Returns
    -------
    output : torch.Tensor
        Per-step output `(batch, output_size)`.
    new_state : torch.Tensor
        Integrated reservoir state `(batch, reservoir_size)`.
    """
    new_state = self._integrate(state, projected_t)
    return self.output_from_state(new_state), new_state

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 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
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
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
>>> 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
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
def __init__(
    self,
    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-6,
    atol: float = 1e-8,
    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: torch.device | str | None = None,
    dtype: torch.dtype | None = None,
) -> None:
    # ``gamma`` is validated by its property setter (shared with live writes);
    # stash the backing field before super().__init__ so the setter is ready,
    # then re-validate below once the object is fully initialised.
    self._gamma: float = 0.0
    # ``spectral_radius`` here targets the *effective* antisymmetric operator
    # ``W_r - W_r^T`` (the rotation rate that actually drives the dynamics),
    # NOT the raw ``W_r``.  The two differ substantially: for a dense random
    # ``W_r`` scaled to radius rho, the skew part ``W_r - W_r^T`` has a much
    # larger imaginary rate (~2x+), which would push the forward-Euler step
    # far past the stable edge and make the state grow without bound.  So we
    # pass ``spectral_radius=None`` to the parent (leaving ``W_r`` un-scaled)
    # and rescale ``weight_hh`` below so ``W_r - W_r^T`` hits the target.
    self._target_skew_radius = spectral_radius
    super().__init__(
        reservoir_size=reservoir_size,
        feedback_size=feedback_size,
        input_size=input_size,
        spectral_radius=None,
        bias=bias,
        bias_scaling=bias_scaling,
        activation=activation,
        trainable=trainable,
        dt=epsilon,
        substeps=substeps,
        solver=solver,
        torchdiffeq_method=torchdiffeq_method,
        rtol=rtol,
        atol=atol,
        feedback_initializer=feedback_initializer,
        input_initializer=input_initializer,
        topology=topology,
        seed=seed,
        recurrent_initializer=recurrent_initializer,
        bias_initializer=bias_initializer,
        initial_state_initializer=initial_state_initializer,
        device=device,
        dtype=dtype,
    )
    # Record the requested target on the base ``spectral_radius`` slot so the
    # ``__repr__`` and any introspection report the meaningful (skew-operator)
    # value rather than ``None``.
    self.spectral_radius = spectral_radius
    if spectral_radius is not None:
        self._scale_skew_spectral_radius(spectral_radius)
    self.gamma = gamma

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

vector_field(state: Tensor, projected_u: Tensor) -> Tensor

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 h, shape (batch, reservoir_size).

TYPE: Tensor

projected_u

Precomputed input drive u = W_fb x_fb + W_in u + b for the interval, shape (batch, reservoir_size).

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

\(\dot h\), shape (batch, reservoir_size).

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
def vector_field(self, state: torch.Tensor, projected_u: torch.Tensor) -> torch.Tensor:
    r"""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).

    Parameters
    ----------
    state : torch.Tensor
        Current state `h`, shape `(batch, reservoir_size)`.
    projected_u : torch.Tensor
        Precomputed input drive `u = W_fb x_fb + W_in u + b` for the
        interval, shape `(batch, reservoir_size)`.

    Returns
    -------
    torch.Tensor
        $\dot h$, shape `(batch, reservoir_size)`.
    """
    # Antisymmetric recurrence W_h = W_r - W_r^T, applied as h (W_r - W_r^T)^T
    # = h W_r^T - h W_r via F.linear conventions.  Compute h @ W_h^T directly:
    # W_h^T = (W_r - W_r^T)^T = W_r^T - W_r, so h @ W_h^T = h @ W_r^T - h @ W_r.
    w = self.weight_hh
    recurrent = state @ w.t() - state @ w
    pre = recurrent - self._gamma * state + projected_u
    return self.activation_fn(pre)

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

v_threshold

Firing threshold \(V_\text{th}\). A neuron spikes when its membrane potential crosses this value from below.

TYPE: float DEFAULT: 1.0

reset

Membrane reset on a spike. 'subtract' does the soft reset \(V \leftarrow V - V_\text{th}\,s\) (preserves overshoot); 'zero' does the hard reset \(V \leftarrow V (1 - s)\).

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

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: float DEFAULT: 10.0

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). 0.0 makes the trace the instantaneous spike; values near 1 give long synaptic memory.

TYPE: float DEFAULT: 0.9

output

Which quantity forward / step return as the readable output. 'trace' (default) is the ridge-regressable filtered spike response — the LSM-correct choice; 'voltage' exposes the raw membrane potential; 'spikes' exposes the binary spike train.

TYPE: (trace, voltage, spikes) DEFAULT: 'trace'

ATTRIBUTE DESCRIPTION
reservoir_size

Hidden dimension of each packed state tensor.

TYPE: int

v_threshold

Firing threshold.

TYPE: float

surrogate_beta

Surrogate slope (live knob).

TYPE: float

trace_decay

Readout-trace decay (live knob).

TYPE: float

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
def __init__(
    self,
    reservoir_size: int,
    v_threshold: float = 1.0,
    reset: str = "subtract",
    surrogate_beta: float = 10.0,
    trace_decay: float = 0.9,
    output: str = "trace",
) -> None:
    super().__init__()

    if reservoir_size <= 0:
        raise ValueError(f"reservoir_size must be a positive integer, got {reservoir_size}")
    if reset not in _VALID_RESETS:
        raise ValueError(f"Unknown reset {reset!r}. Supported: {sorted(_VALID_RESETS)}.")
    if output not in _VALID_OUTPUTS:
        raise ValueError(f"Unknown output {output!r}. Supported: {sorted(_VALID_OUTPUTS)}.")

    self.reservoir_size = reservoir_size
    self.v_threshold = float(v_threshold)
    self.reset = reset
    self._output = output

    # ``surrogate_beta`` / ``trace_decay`` are live knobs validated by their
    # property setters (shared by the constructor and post-init writes).
    self._surrogate_beta: float = 10.0
    self._trace_decay: float = 0.0
    self.surrogate_beta = surrogate_beta
    self.trace_decay = trace_decay

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

output property

output: str

str : Readable-output mode ('trace' | 'voltage' | 'spikes').

init_state

init_state(batch_size: int, device: device, dtype: dtype) -> Tensor

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
def init_state(
    self,
    batch_size: int,
    device: torch.device,
    dtype: torch.dtype,
) -> torch.Tensor:
    """Return a zero packed state of shape `(batch_size, state_size)`."""
    return torch.zeros(batch_size, self.state_size, device=device, dtype=dtype)

spike

spike(v: Tensor) -> Tensor

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 (batch, reservoir_size).

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Binary spike tensor (values in {0, 1}), same shape as v, with a surrogate gradient w.r.t. v.

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
def spike(self, v: torch.Tensor) -> torch.Tensor:
    r"""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`.

    Parameters
    ----------
    v : torch.Tensor
        Membrane potential, shape `(batch, reservoir_size)`.

    Returns
    -------
    torch.Tensor
        Binary spike tensor (values in `{0, 1}`), same shape as `v`,
        with a surrogate gradient w.r.t. `v`.
    """
    shifted = v - self.v_threshold
    hard = (shifted > 0).to(v.dtype)
    surrogate = torch.sigmoid(self._surrogate_beta * shifted)
    return surrogate + (hard - surrogate).detach()

apply_reset

apply_reset(v: Tensor, spikes: Tensor) -> Tensor

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 (batch, reservoir_size).

TYPE: Tensor

spikes

Spike tensor from spike, same shape.

TYPE: Tensor

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
def apply_reset(self, v: torch.Tensor, spikes: torch.Tensor) -> torch.Tensor:
    r"""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`.

    Parameters
    ----------
    v : torch.Tensor
        Post-integration membrane potential, shape `(batch, reservoir_size)`.
    spikes : torch.Tensor
        Spike tensor from `spike`, same shape.

    Returns
    -------
    torch.Tensor
        The reset membrane potential.
    """
    if self.reset == "zero":
        return v * (1.0 - spikes)
    return v - self.v_threshold * spikes

update_trace

update_trace(trace: Tensor, spikes: Tensor) -> Tensor

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 r_{t-1}, shape (batch, reservoir_size).

TYPE: Tensor

spikes

Current spikes s_t, same shape.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Updated trace r_t.

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
def update_trace(self, trace: torch.Tensor, spikes: torch.Tensor) -> torch.Tensor:
    r"""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.

    Parameters
    ----------
    trace : torch.Tensor
        Previous trace `r_{t-1}`, shape `(batch, reservoir_size)`.
    spikes : torch.Tensor
        Current spikes `s_t`, same shape.

    Returns
    -------
    torch.Tensor
        Updated trace `r_t`.
    """
    return self._trace_decay * trace + spikes

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 n_neuron_tensors neuron state tensors in packing order — (V,) for first-order LIF, (I, V) for CuBa-LIF — each of shape (batch, reservoir_size).

TYPE: tuple of torch.Tensor

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 LIFCell), shape (batch, reservoir_size).

TYPE: Tensor

RETURNS DESCRIPTION
new_neuron_state

The updated neuron tensors in the same packing order.

TYPE: tuple of torch.Tensor

spikes

The binary spike tensor emitted this step, shape (batch, reservoir_size) (carries the surrogate gradient).

TYPE: Tensor

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
@abstractmethod
def neuron_update(
    self,
    neuron_state: tuple[torch.Tensor, ...],
    projected_input: torch.Tensor,
) -> tuple[tuple[torch.Tensor, ...], torch.Tensor]:
    r"""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.

    Parameters
    ----------
    neuron_state : tuple of torch.Tensor
        The `n_neuron_tensors` neuron state tensors in packing order —
        `(V,)` for first-order LIF, `(I, V)` for CuBa-LIF — each of shape
        `(batch, reservoir_size)`.
    projected_input : torch.Tensor
        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 `LIFCell`), shape
        `(batch, reservoir_size)`.

    Returns
    -------
    new_neuron_state : tuple of torch.Tensor
        The updated neuron tensors in the same packing order.
    spikes : torch.Tensor
        The binary spike tensor emitted this step, shape
        `(batch, reservoir_size)` (carries the surrogate gradient).
    """
    ...

project_inputs abstractmethod

project_inputs(inputs: list[Tensor]) -> Tensor

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
@abstractmethod
def project_inputs(self, inputs: list[torch.Tensor]) -> torch.Tensor:
    """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`).
    """
    ...

forward

forward(inputs: list[Tensor], state: Tensor) -> tuple[Tensor, Tensor]

Advance one timestep: project inputs, then step.

PARAMETER DESCRIPTION
inputs

inputs[0] feedback (batch, feedback_size); inputs[1] (optional) driving input (batch, input_size).

TYPE: list[Tensor]

state

Current packed state (batch, state_size).

TYPE: Tensor

RETURNS DESCRIPTION
output

Readable per-step output (batch, reservoir_size) (see output).

TYPE: Tensor

new_state

Updated packed state (batch, state_size).

TYPE: Tensor

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
def forward(
    self,
    inputs: list[torch.Tensor],
    state: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
    """Advance one timestep: project inputs, then `step`.

    Parameters
    ----------
    inputs : list[torch.Tensor]
        `inputs[0]` feedback `(batch, feedback_size)`; `inputs[1]`
        (optional) driving input `(batch, input_size)`.
    state : torch.Tensor
        Current packed state `(batch, state_size)`.

    Returns
    -------
    output : torch.Tensor
        Readable per-step output `(batch, reservoir_size)` (see
        `output`).
    new_state : torch.Tensor
        Updated packed state `(batch, state_size)`.
    """
    projected = self.project_inputs(inputs)
    return self.step(projected, state)

step

step(projected_t: Tensor, state: Tensor) -> tuple[Tensor, Tensor]

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 (batch, reservoir_size).

TYPE: Tensor

state

Current packed state (batch, state_size).

TYPE: Tensor

RETURNS DESCRIPTION
output

Readable per-step output (batch, reservoir_size).

TYPE: Tensor

new_state

Updated packed state (batch, state_size).

TYPE: Tensor

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
def step(
    self,
    projected_t: torch.Tensor,
    state: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
    r"""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.

    Parameters
    ----------
    projected_t : torch.Tensor
        Precomputed input drive for this step, shape
        `(batch, reservoir_size)`.
    state : torch.Tensor
        Current packed state `(batch, state_size)`.

    Returns
    -------
    output : torch.Tensor
        Readable per-step output `(batch, reservoir_size)`.
    new_state : torch.Tensor
        Updated packed state `(batch, state_size)`.
    """
    tensors = _split_state(state, self.reservoir_size)
    neuron_state = tensors[:-1]
    trace = tensors[-1]

    new_neuron_state, spikes = self.neuron_update(neuron_state, projected_t)
    new_trace = self.update_trace(trace, spikes)

    new_state = _pack_state(*new_neuron_state, new_trace)
    # The neuron tensors always END with the current spikes ``s``
    # (``[V | s]`` or ``[I | V | s]``), so the membrane potential ``V`` is the
    # *second-to-last* neuron tensor — that is what the "voltage" mode reads.
    v = new_neuron_state[-2]
    output = self._select_output(new_trace, v, spikes)
    return output, new_state

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

feedback_size

Dimension of the feedback signal. Required.

TYPE: int

input_size

Dimension of an optional driving input. None (or 0) builds a feedback-only cell.

TYPE: int DEFAULT: None

tau_mem

Membrane time constant \(\tau_\text{mem} > 0\) (same time units as dt). Sets the membrane decay \(\beta = e^{-\Delta t/\tau_\text{mem}}\).

TYPE: float DEFAULT: 20.0

tau_syn

Synaptic time constant \(\tau_\text{syn} > 0\). Only used when synaptic_current=True (CuBa-LIF); sets \(\alpha = e^{-\Delta t/\tau_\text{syn}}\).

TYPE: float DEFAULT: 10.0

dt

Integration timestep \(\Delta t > 0\).

TYPE: float DEFAULT: 1.0

synaptic_current

If True, use the second-order CuBa-LIF model with an explicit synaptic-current state I; otherwise the first-order LIF.

TYPE: bool DEFAULT: False

v_threshold

Firing threshold (see SpikingReservoirCell).

TYPE: float DEFAULT: 1.0

reset

Membrane reset on a spike (see SpikingReservoirCell).

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

surrogate_beta

Fast-sigmoid surrogate slope for the straight-through spike gradient.

TYPE: float DEFAULT: 10.0

trace_decay

Decay of the low-pass readout trace (the cell's real-valued output).

TYPE: float DEFAULT: 0.9

output

Readable-output mode. 'trace' (default) is the ridge-regressable filtered spike response — the LSM-correct choice.

TYPE: (trace, voltage, spikes) DEFAULT: 'trace'

spectral_radius

Target spectral radius for W_rec. Scales the recurrent spike-coupling strength (how strongly one neuron's spikes drive its neighbours). None leaves W_rec unscaled.

TYPE: float DEFAULT: None

bias

Whether to include a bias current b.

TYPE: bool DEFAULT: True

bias_scaling

Scale of the random bias (uniform(-bias_scaling, bias_scaling)).

TYPE: float DEFAULT: 1.0

trainable

If True, all weights participate in backpropagation (through the surrogate spike gradient). Frozen LSMs use False.

TYPE: bool DEFAULT: False

feedback_initializer

Initializers for the feedback / driving-input weights. Same accepted forms as resdag.layers.cells.esn_cell.ESNCell.

TYPE: spec DEFAULT: None

input_initializer

Initializers for the feedback / driving-input weights. Same accepted forms as resdag.layers.cells.esn_cell.ESNCell.

TYPE: spec DEFAULT: None

topology

Structure of the recurrent weight W_rec. Same forms as ESNCell.

TYPE: spec DEFAULT: None

seed

Reproducibility seed for independent weight, bias and reset-state roles. Integers and a generator's initial_seed() do not advance the caller's RNG. None draws one master seed from Torch's CPU global RNG. Explicit initializer seeds and callback-owned generators retain their own policy.

TYPE: int or Generator DEFAULT: None

recurrent_initializer

First-class alias for topology. Supply one spelling only. Names, tuples, callables and registered initializer objects are accepted.

TYPE: spec DEFAULT: None

bias_initializer

Input/feedback initializer grammar applied to a (1, reservoir_size) view of the bias. Requires bias=True; overrides bias_scaling.

TYPE: spec DEFAULT: None

initial_state_initializer

Initializes a persistent (1, cell.state_size) reset template once. Each batch example receives an independent copy at reset. Zero by default.

TYPE: spec DEFAULT: None

device

Initial parameter location. Metal construction initializes on CPU before transferring to support initialization operations across backends.

TYPE: device or str DEFAULT: None

dtype

Floating precision used during initialization, not only after conversion.

TYPE: dtype DEFAULT: None

ATTRIBUTE DESCRIPTION
beta

Membrane decay \(\beta = e^{-\Delta t/\tau_\text{mem}}\) (derived).

TYPE: float

alpha

Synaptic-current decay \(\alpha = e^{-\Delta t/\tau_\text{syn}}\) (derived; only meaningful when synaptic_current=True).

TYPE: float

weight_rec

Recurrent spike-coupling weight W_rec, shape (reservoir_size, reservoir_size).

TYPE: Parameter

weight_feedback

Feedback weight W_fb, shape (reservoir_size, feedback_size).

TYPE: Parameter

weight_input

Driving-input weight W_in, shape (reservoir_size, input_size), or None.

TYPE: Parameter or None

bias_h

Bias current b, shape (reservoir_size,), or None.

TYPE: Parameter or None

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
def __init__(
    self,
    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: torch.device | str | None = None,
    dtype: torch.dtype | None = None,
) -> None:
    # First-order LIF packs [V | s | r] (3 tensors); CuBa-LIF packs
    # [I | V | s | r] (4).  Set the count BEFORE super().__init__ so
    # ``state_size`` is correct the moment the base needs it.
    self.synaptic_current = bool(synaptic_current)
    self.n_state_tensors = 4 if self.synaptic_current else 3

    super().__init__(
        reservoir_size=reservoir_size,
        v_threshold=v_threshold,
        reset=reset,
        surrogate_beta=surrogate_beta,
        trace_decay=trace_decay,
        output=output,
    )

    self.feedback_size = feedback_size
    # Treat input_size == 0 the same as None (no driving-input weights),
    # matching ESNCell and the premade factories.
    self.input_size = input_size if input_size else None
    self.tau_mem = float(tau_mem)
    self.tau_syn = float(tau_syn)
    self.dt = float(dt)

    self.topology = select_recurrent_spec(
        topology=topology, recurrent_initializer=recurrent_initializer
    )
    if dtype is not None and not dtype.is_floating_point:
        raise ValueError("Reservoir dtype must be floating point")
    if not bias and bias_initializer is not None:
        raise ValueError("bias_initializer requires bias=True")
    self.bias_initializer = bias_initializer
    self.initial_state_initializer = initial_state_initializer
    target_device = torch.device(device) if device is not None else torch.empty(0).device
    if target_device.type == "mps" and (dtype or torch.get_default_dtype()) == torch.float64:
        raise TypeError("MPS does not support float64; use float32 or CPU")
    # Initialize on CPU before a Metal transfer for portable RNG/linalg support.
    init_device = "cpu" if target_device is not None and target_device.type == "mps" else device
    self._factory_kwargs: dict[str, Any] = {"device": init_device, "dtype": dtype}
    self.spectral_radius = spectral_radius
    self.feedback_initializer = feedback_initializer
    self.input_initializer = input_initializer
    self._bias = bias
    self.bias_scaling = bias_scaling

    self.seed = seed
    self._seed_int = coerce_seed_to_int(seed)
    if self._seed_int is None:
        self._seed_int = int(torch.randint(0, 2**63 - 1, (1,), device="cpu").item())
    self._trainable = trainable

    self._initialize_weights()
    install_initial_state(
        self,
        self.initial_state_initializer,
        seed=_salt_seed(self._seed_int, 0x9E3779B9 * 7),
        state_size=self.state_size,
        reference=self.weight_feedback,
    )

    # Apply the requested freeze through the base property so construction and
    # post-init ``cell.trainable = ...`` share one code path.
    self.trainable = trainable
    if target_device is not None and target_device.type == "mps":
        self.to(target_device)

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.

dt property writable

dt: float

Live integration interval; updating it recomputes 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

init_state(batch_size: int, device: device, dtype: dtype) -> Tensor

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
def init_state(self, batch_size: int, device: torch.device, dtype: torch.dtype) -> torch.Tensor:
    """Initialize packed neuron and trace state; zero by default."""
    return initialized_state(
        self,
        batch_size,
        self.state_size,
        device,
        dtype,
    )

project_inputs

project_inputs(inputs: list[Tensor]) -> Tensor

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

inputs[0] feedback; inputs[1] (optional) driving input.

TYPE: list[Tensor]

RETURNS DESCRIPTION
Tensor

Input drive with the inputs' leading dims and trailing dimension reservoir_size.

RAISES DESCRIPTION
ValueError

On a feedback / driving-input feature-dimension mismatch, or if a driving input is supplied to a cell built without input_size.

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
def project_inputs(self, inputs: list[torch.Tensor]) -> torch.Tensor:
    """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.

    Parameters
    ----------
    inputs : list[torch.Tensor]
        `inputs[0]` feedback; `inputs[1]` (optional) driving input.

    Returns
    -------
    torch.Tensor
        Input drive with the inputs' leading dims and trailing dimension
        `reservoir_size`.

    Raises
    ------
    ValueError
        On a feedback / driving-input feature-dimension mismatch, or if a
        driving input is supplied to a cell built without `input_size`.
    """
    fb = inputs[0]
    if fb.shape[-1] != self.feedback_size:
        raise ValueError(
            f"Feedback size mismatch. Expected {self.feedback_size}, got {fb.shape[-1]}"
        )
    drive = F.linear(fb, self.weight_feedback)

    if len(inputs) > 1:
        if self.weight_input is None:
            raise ValueError(
                "Reservoir was initialized without input_size, "
                "but driving input was provided in forward pass"
            )
        x = inputs[1]
        if x.shape[-1] != self.input_size:
            raise ValueError(
                f"Driving input size mismatch. Expected {self.input_size}, got {x.shape[-1]}"
            )
        drive = drive + F.linear(x, self.weight_input)

    if self.bias_h is not None:
        drive = drive + self.bias_h

    return drive

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

(V, s) for first-order LIF or (I, V, s) for CuBa-LIF, each of shape (batch, reservoir_size). s is the previous step's spikes (recurrent input); I / V the current / membrane states.

TYPE: tuple of torch.Tensor

projected_input

Precomputed analog drive W_fb x_fb + W_in u + b, shape (batch, reservoir_size).

TYPE: Tensor

RETURNS DESCRIPTION
new_neuron_state

(V_new, s_new) or (I_new, V_new, s_new) in packing order.

TYPE: tuple of torch.Tensor

spikes

The spikes emitted this step (== s_new), carrying the surrogate gradient.

TYPE: Tensor

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
def neuron_update(
    self,
    neuron_state: tuple[torch.Tensor, ...],
    projected_input: torch.Tensor,
) -> tuple[tuple[torch.Tensor, ...], torch.Tensor]:
    r"""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`.

    Parameters
    ----------
    neuron_state : tuple of torch.Tensor
        `(V, s)` for first-order LIF or `(I, V, s)` for CuBa-LIF, each of
        shape `(batch, reservoir_size)`.  `s` is the previous step's
        spikes (recurrent input); `I` / `V` the current / membrane states.
    projected_input : torch.Tensor
        Precomputed analog drive `W_fb x_fb + W_in u + b`, shape
        `(batch, reservoir_size)`.

    Returns
    -------
    new_neuron_state : tuple of torch.Tensor
        `(V_new, s_new)` or `(I_new, V_new, s_new)` in packing order.
    spikes : torch.Tensor
        The spikes emitted this step (`== s_new`), carrying the surrogate
        gradient.
    """
    # Complete the drive with the recurrent spike-coupling term.
    recurrent = F.linear(neuron_state[-1], self.weight_rec)
    drive = projected_input + recurrent

    if self.synaptic_current:
        i_prev, v_prev = neuron_state[0], neuron_state[1]
        i_new = self.alpha * i_prev + drive
        v_pre = self.beta * v_prev + (1.0 - self.beta) * i_new
        spikes = self.spike(v_pre)
        v_new = self.apply_reset(v_pre, spikes)
        return (i_new, v_new, spikes), spikes

    v_prev = neuron_state[0]
    v_pre = self.beta * v_prev + (1.0 - self.beta) * drive
    spikes = self.spike(v_pre)
    v_new = self.apply_reset(v_pre, spikes)
    return (v_new, spikes), spikes

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
def __init__(
    self,
    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: torch.device | str | None = None,
    dtype: torch.dtype | None = None,
) -> None:
    device = torch.device(device) if device is not None else torch.get_default_device()
    size = positive_size("reservoir_size", reservoir_size)
    dt = finite_scalar("dt", dt, positive=True)
    gamma = finite_scalar("gamma", gamma)
    epsilon = finite_scalar("epsilon", epsilon)
    if spectral_radius is not None:
        spectral_radius = finite_scalar("spectral_radius", spectral_radius)
    position_spec = select_recurrent_spec(
        topology=topology, recurrent_initializer=recurrent_initializer
    )
    super().__init__(
        size,
        feedback_size,
        input_size,
        bias=bias,
        bias_scaling=bias_scaling,
        feedback_initializer=feedback_initializer,
        input_initializer=input_initializer,
        seed=seed,
        device=device,
        dtype=dtype,
    )
    self.reservoir_size = size
    self.dt = dt
    self.gamma = gamma
    self.epsilon = epsilon
    self.spectral_radius = spectral_radius
    self.weight_hh = nn.Parameter(
        torch.empty(size, size, device=self.weight_feedback.device, dtype=dtype),
        requires_grad=False,
    )
    self.weight_hv = nn.Parameter(
        torch.empty(size, size, device=self.weight_feedback.device, dtype=dtype),
        requires_grad=False,
    )
    for weight, spec, offset, radius in (
        (self.weight_hh, position_spec, 41, spectral_radius),
        (self.weight_hv, velocity_initializer, 53, None),
    ):
        initializer = resolve_recurrent_initializer(spec, seed=role_seed(seed, offset))
        with torch.no_grad():
            if initializer is None:
                bound = 1.0 / math.sqrt(size)
                nn.init.uniform_(
                    weight,
                    -bound,
                    bound,
                    generator=create_torch_generator(role_seed(seed, offset), weight.device),
                )
                if radius is not None:
                    weight.copy_(scale_to_spectral_radius(weight, radius))
            else:
                weight.copy_(initializer.initialize(weight, spectral_radius=radius))
            if not torch.isfinite(weight).all():
                raise ValueError("Recurrent initializer produced non-finite weights")
    self.trainable = trainable
    if device is not None and torch.device(device).type == "mps":
        self.to(device)

dt property writable

dt: float

Positive integration interval; assignments affect the next update.

gamma property writable

gamma: float

Nonnegative position restoring coefficient.

epsilon property writable

epsilon: float

Nonnegative velocity damping coefficient.

state_size property

state_size: int

Packed position-plus-velocity width, twice reservoir_size.

output_size property

output_size: int

Position output width, equal to reservoir_size.

step

step(projected_t: Tensor, state: Tensor) -> tuple[Tensor, Tensor]

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
def step(self, projected_t: Tensor, state: Tensor) -> tuple[Tensor, Tensor]:
    """Return updated positions and packed position/velocity state for one frame."""
    self._check_step(projected_t, state, self.reservoir_size)
    h, v = state.split(self.reservoir_size, dim=-1)
    force = torch.tanh(projected_t + F.linear(h, self.weight_hh) + F.linear(v, self.weight_hv))
    new_v = v + self.dt * (force - self.gamma * h - self.epsilon * v)
    new_h = h + self.dt * new_v
    return new_h, torch.cat((new_h, new_v), dim=-1)

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.

Reference: https://papers.nips.cc/paper/9689-legendre-memory-units-continuous-time-representation-in-recurrent-neural-networks

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
def __init__(
    self,
    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: torch.device | str | None = None,
    dtype: torch.dtype | None = None,
) -> None:
    device = torch.device(device) if device is not None else torch.get_default_device()
    order = positive_size("order", order)
    positive_size("feedback_size", feedback_size)
    if input_size is not None:
        positive_size("input_size", input_size)
    total_width = feedback_size + (input_size or 0)
    channels = (
        total_width
        if memory_channels is None
        else positive_size("memory_channels", memory_channels)
    )
    theta = finite_scalar("theta", theta, positive=True)
    dt = finite_scalar("dt", dt, positive=True)
    super().__init__(
        channels,
        feedback_size,
        input_size,
        bias=False,
        bias_scaling=0.0,
        feedback_initializer=feedback_initializer,
        input_initializer=input_initializer,
        seed=seed,
        device=device,
        dtype=dtype,
    )
    self._order = order
    self._memory_channels = channels
    self.reservoir_size = order * channels
    self._theta = theta
    self._dt = dt
    with torch.no_grad():
        if channels == total_width:
            encoder = torch.eye(
                channels, device=self.weight_feedback.device, dtype=self.weight_feedback.dtype
            )
            if feedback_initializer is None:
                self.weight_feedback.copy_(encoder[:, :feedback_size])
            if input_initializer is None and self.weight_input is not None:
                self.weight_input.copy_(encoder[:, feedback_size:])
        else:
            scale = 1.0 / math.sqrt(total_width)
            if feedback_initializer is None:
                self.weight_feedback.mul_(scale)
            if input_initializer is None and self.weight_input is not None:
                self.weight_input.mul_(scale)
    # Half/bfloat matrix_exp is not numerically supported. Compute once in
    # float32 then cast; requested float64 remains float64 throughout.
    parameter_dtype = self.weight_feedback.dtype
    work_dtype = torch.float64 if parameter_dtype == torch.float64 else torch.float32
    i = torch.arange(order, device=self.weight_feedback.device)
    rows, columns = i[:, None], i[None, :]
    sign = torch.where((rows - columns + 1).remainder(2) == 0, 1.0, -1.0)
    A = ((2 * rows + 1).to(work_dtype) * torch.where(rows < columns, -1.0, sign)) / theta
    B = ((2 * i + 1).to(work_dtype) * torch.where(i.remainder(2) == 0, 1.0, -1.0)) / theta
    if not torch.isfinite(A).all() or not torch.isfinite(B).all():
        raise ValueError(
            "theta/order produce non-finite continuous memory dynamics in the requested dtype"
        )
    augmented = torch.zeros(order + 1, order + 1, device=A.device, dtype=work_dtype)
    augmented[:order, :order] = A
    augmented[:order, order] = B
    scaled = augmented * dt
    # A finite elementwise matrix can still overflow norm estimation or
    # require an unreasonable number of scaling/squaring iterations. Bound
    # the numerical work before entering the backend (which may otherwise
    # hang on Inf or extreme finite inputs). Ordinary memory-window ratios
    # are many orders below this limit.
    norm = torch.linalg.matrix_norm(scaled, ord=1)
    if not torch.isfinite(norm) or norm > 2**20:
        raise ValueError(
            "dt/theta/order exceed the supported ZOH matrix 1-norm (2**20); "
            "reduce dt/theta or order"
        )
    if order == 1:
        # The order-1 system is a scalar leaky integrator. Its closed form
        # also avoids roundoff in matrix_exp's small 2x2 approximation.
        exponent = A[0, 0] * dt
        discrete_A = exponent.exp().reshape(1, 1)
        discrete_B = -exponent.expm1().reshape(1)
    else:
        transition = torch.matrix_exp(scaled)
        discrete_A = transition[:order, :order]
        discrete_B = transition[:order, order]
    self.continuous_A: Tensor
    self.continuous_B: Tensor
    self.register_buffer("continuous_A", A.to(parameter_dtype))
    self.register_buffer("continuous_B", B.to(parameter_dtype))
    self.register_buffer("A", discrete_A.to(parameter_dtype).contiguous())
    self.register_buffer("B", discrete_B.to(parameter_dtype).contiguous())
    if any(
        not torch.isfinite(value).all()
        for value in (self.continuous_A, self.continuous_B, self.A, self.B)
    ):
        raise ValueError(
            "theta/dt/order produce non-finite memory dynamics in the requested dtype"
        )
    self.trainable = trainable
    if device is not None and torch.device(device).type == "mps":
        self.to(device)

order property

order: int

Number of Legendre coefficients retained per memory channel.

memory_channels property

memory_channels: int

Number of independently encoded input channels.

theta property

theta: float

Memory-window length used when constructing the fixed dynamics.

dt property

dt: float

Sampling interval used to discretize the memory dynamics.

state_size property

state_size: int

Packed memory width, memory_channels * order.

output_size property

output_size: int

Readable memory width, equal to state_size.

step

step(projected_t: Tensor, state: Tensor) -> tuple[Tensor, Tensor]

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
def step(self, projected_t: Tensor, state: Tensor) -> tuple[Tensor, Tensor]:
    """Advance one zero-order-hold interval and return readable and carried memory."""
    self._check_step(projected_t, state, self.memory_channels)
    memory = state.reshape(state.shape[0], self.memory_channels, self.order)
    new_memory = memory @ self.A.T + projected_t.unsqueeze(-1) * self.B
    output = new_memory.reshape(state.shape[0], self.state_size)
    return output, output

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
def __init__(
    self,
    cell: nn.GRUCell | nn.LSTMCell,
    feedback_size: int,
    input_size: int | None = None,
    *,
    trainable: bool = False,
) -> None:
    super().__init__()
    if type(cell) not in (nn.GRUCell, nn.LSTMCell):
        raise TypeError("cell must be a standard torch.nn.GRUCell or torch.nn.LSTMCell")
    self.feedback_size = positive_size("feedback_size", feedback_size)
    self.input_size = None if input_size is None else positive_size("input_size", input_size)
    total_width = feedback_size + (input_size or 0)
    if cell.input_size != total_width:
        raise ValueError(
            f"Native cell input_size must equal feedback plus driver width ({total_width})"
        )
    self.recurrent_cell = deepcopy(cell)
    self.reservoir_size = cell.hidden_size
    self._is_lstm = isinstance(cell, nn.LSTMCell)
    self.trainable = trainable

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

init_state(batch_size: int, device: device, dtype: dtype) -> Tensor

Return zero initial hidden state, including LSTM carry when applicable.

Source code in src/resdag/layers/cells/torch_recurrent_cell.py
79
80
81
def init_state(self, batch_size: int, device: torch.device, dtype: torch.dtype) -> Tensor:
    """Return zero initial hidden state, including LSTM carry when applicable."""
    return torch.zeros(batch_size, self.state_size, device=device, dtype=dtype)

project_inputs

project_inputs(inputs: list[Tensor]) -> Tensor

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
def project_inputs(self, inputs: list[Tensor]) -> Tensor:
    """Project feedback and optional driver into the native cell's input gates."""
    validate_inputs(inputs, self.feedback_size, self.input_size)
    combined = inputs[0] if self.input_size is None else torch.cat(inputs, dim=-1)
    cell = self.recurrent_cell
    return F.linear(combined, cell.weight_ih, cell.bias_ih)

step

step(projected_t: Tensor, state: Tensor) -> tuple[Tensor, Tensor]

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
def step(self, projected_t: Tensor, state: Tensor) -> tuple[Tensor, Tensor]:
    """Advance one projected frame and return hidden output and carried state."""
    self.validate_state(state)
    gates = 4 if self._is_lstm else 3
    if projected_t.ndim != 2 or projected_t.shape != (
        state.shape[0],
        gates * self.reservoir_size,
    ):
        raise ValueError(
            f"Projected timestep must have shape (batch, {gates * self.reservoir_size})"
        )
    cell = self.recurrent_cell
    h = state[:, : self.reservoir_size]
    recurrent = F.linear(h, cell.weight_hh, cell.bias_hh)
    if self._is_lstm:
        i, f, g, o = (projected_t + recurrent).chunk(4, dim=-1)
        c = state[:, self.reservoir_size :]
        new_c = f.sigmoid() * c + i.sigmoid() * g.tanh()
        new_h = o.sigmoid() * new_c.tanh()
        return new_h, torch.cat((new_h, new_c), dim=-1)
    ir, iz, inn = projected_t.chunk(3, dim=-1)
    hr, hz, hn = recurrent.chunk(3, dim=-1)
    reset = (ir + hr).sigmoid()
    update = (iz + hz).sigmoid()
    candidate = (inn + reset * hn).tanh()
    # Match native arithmetic ordering, including promotion under autocast.
    new_h = candidate + update * (h - candidate)
    return new_h, new_h

forward

forward(inputs: list[Tensor], state: Tensor) -> tuple[Tensor, Tensor]

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
def forward(self, inputs: list[Tensor], state: Tensor) -> tuple[Tensor, Tensor]:
    """Advance one raw feedback/driver frame using the native GRU/LSTM equations."""
    return self.step(self.project_inputs(inputs), state)

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

feedback_size

Dimension of feedback signal. Required for all reservoirs.

TYPE: int

input_size

Dimension of driving inputs. If None, no driving input is expected.

TYPE: int DEFAULT: None

spectral_radius

Target spectral radius for recurrent weights. Controls the "memory" and stability of the reservoir. If None, no spectral radius scaling is applied.

TYPE: float DEFAULT: None

bias

Whether to include a bias term.

TYPE: bool DEFAULT: True

bias_scaling

Scale of the random bias: entries are drawn from uniform(-bias_scaling, bias_scaling). Set to 0.0 for a zero bias (pre-0.5 behaviour). Ignored when bias=False.

TYPE: float DEFAULT: 1.0

activation

Activation function for reservoir dynamics.

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

leak_rate

Leaky integration rate in (0, 1]. A scalar 1.0 means no leaking (standard RNN update); smaller values create slower dynamics. A 1-D tensor/sequence of length reservoir_size assigns a per-neuron leak (heterogeneous timescales in one reservoir, matching RC.jl's leak_coefficient vector); every entry must be finite and in (0, 1]. See resdag.layers.cells.esn_cell.ESNCell for the full contract (a vector leak is stored as a buffer that moves with .to() / .double() and round-trips through save/load).

TYPE: float or 1-D tensor/sequence of shape `(reservoir_size,)` DEFAULT: 1.0

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 torch.nn.Module.eval. The default 0.0 disables it, leaving outputs bit-identical to the noiseless layer. Reproducible under the layer's seed. Must be non-negative.

TYPE: float DEFAULT: 0.0

trainable

If True, reservoir weights are trainable via backpropagation. Standard ESNs use frozen (non-trainable) weights.

TYPE: bool DEFAULT: False

sparse

False keeps dense recurrent weights. True stores frozen weights only as compressed CSR components; weight_hh is a zero-copy CSR view. Use weight_hh.to_dense() for explicit inspection. "auto" uses size/density heuristics, not hardware calibration. Compact storage saves recurrent-weight memory but does not guarantee faster execution or remove sequence/readout allocations. See resdag.layers.cells.ESNCell for initialization, numerical, device and trainability boundaries.

TYPE: bool or {auto} DEFAULT: False

feedback_initializer

Initializer for the feedback weight matrix. Accepts a registry name, (name, params), any matrix-building callable fn(rows, cols, **kw) -> matrix (or in-place fn(tensor), e.g. torch.nn.init.xavier_uniform_), (callable, params), or a configured initializer object.

TYPE: str, callable, tuple, or InputFeedbackInitializer DEFAULT: None

input_initializer

Initializer for the input weight matrix. Same formats as feedback_initializer. Only used when input_size is provided.

TYPE: str, callable, tuple, or InputFeedbackInitializer DEFAULT: None

topology

Structure of the recurrent weight matrix. Accepts a registry name (graph or matrix topology), (name, params), any matrix-building callable fn(n, **kw) -> matrix | nx.Graph (or in-place fn(tensor)), (callable, params), or a configured topology object.

TYPE: str, callable, tuple, or TopologyInitializer DEFAULT: None

recurrent_initializer

First-class alias for topology accepting graph and matrix builders, registered names and custom callables. Supply only one of the two.

TYPE: str, callable, tuple, or TopologyInitializer DEFAULT: None

bias_initializer

Override the default random bias. Uses the same formats as input initialization on a (1, reservoir_size) tensor, then flattens to the bias vector. Requires bias=True. Explicit hook values take precedence over bias_scaling.

TYPE: str, callable, tuple, or InputFeedbackInitializer DEFAULT: None

initial_state_initializer

Initialize a persistent (1, reservoir_size) state template once at construction. Every reset broadcasts an independent copy to each batch item. None keeps the zero-state default. The template moves with .to() and is included in checkpoints.

TYPE: str, callable, tuple, or InputFeedbackInitializer DEFAULT: None

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.

TYPE: device or str DEFAULT: None

dtype

Floating-point initialization precision. Defaults to Torch's default dtype. torch.float64 constructs in double precision rather than rounding float32 weights and converting afterward.

TYPE: dtype DEFAULT: None

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 int or a torch.Generator (handy for threading a per-trial generator from an HPO loop). This covers both explicit initializers/topologies and the default uniform(-1, 1) draws used when none is given. With seed set, a string-form topology='erdos_renyi' is reproducible without the ('erdos_renyi', {'seed': ...}) tuple form; an explicit seed in a tuple/object spec always wins. When seed=None (the default), the reservoir is still reproducible under torch.manual_seed because every generator (NumPy and torch) is derived from torch's global RNG.

TYPE: int or Generator DEFAULT: None

ATTRIBUTE DESCRIPTION
state

Current reservoir state of shape (batch, reservoir_size). None if not yet initialized.

TYPE: Tensor or None

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
def __init__(
    self,
    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: torch.device | str | None = None,
    dtype: torch.dtype | None = None,
) -> None:
    cell = ESNCell(
        reservoir_size=reservoir_size,
        feedback_size=feedback_size,
        input_size=input_size,
        spectral_radius=spectral_radius,
        bias=bias,
        bias_scaling=bias_scaling,
        activation=activation,
        leak_rate=leak_rate,
        noise=noise,
        trainable=trainable,
        sparse=sparse,
        feedback_initializer=feedback_initializer,
        input_initializer=input_initializer,
        topology=topology,
        seed=seed,
        recurrent_initializer=recurrent_initializer,
        bias_initializer=bias_initializer,
        initial_state_initializer=initial_state_initializer,
        device=device,
        dtype=dtype,
    )
    super().__init__(cell)

BaseReservoirLayer

BaseReservoirLayer(cell: ReservoirCell)

Bases: Module, ABC

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

ATTRIBUTE DESCRIPTION
cell

The wrapped single-step cell.

TYPE: ReservoirCell

state

Current reservoir state, or None if not yet initialized. The layout is cell-defined: 2-D (batch, cell.state_size) for resdag.layers.cells.esn_cell.ESNCell, 3-D (batch, cell.state_size, input_dim) delay buffer for resdag.layers.cells.ngrc_cell.NGCell. See ReservoirCell.state_size <resdag.layers.cells.base_cell.ReservoirCell.state_size> for the leading state dimension.

TYPE: Tensor or None

detach_state_between_calls

If True (default), the stored state is detached from the autograd graph at the end of each forward call (truncated BPTT at call boundaries). Gradients still flow through the returned states within a call — this only severs gradient flow across calls, which otherwise raises "backward through the graph a second time" when a model is trained with SGD over consecutive batches without resetting the reservoir. Set to False only if you intentionally backprop through state carried across multiple forward calls (and manage the retained graphs yourself).

TYPE: bool

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
def __init__(self, cell: ReservoirCell) -> None:
    super().__init__()
    self.cell = cell
    # Register the reservoir state as a *non-persistent* buffer so that
    # ``nn.Module._apply`` (driven by ``.to()`` / ``.cuda()`` / ``.double()``)
    # moves a warmed-up state along with the module's parameters, instead of
    # leaving it on the original device/dtype and triggering a silent
    # zero-reinit on the next forward.  ``persistent=False`` keeps it out of
    # ``state_dict()`` so the ``save`` / ``include_states`` split is
    # untouched.  The buffer is initialised to ``None`` and reassigned with a
    # concrete tensor on first use (buffers accept reassignment, including
    # back to ``None`` for lazy re-init).
    self.register_buffer("state", None, persistent=False)
    self.state: torch.Tensor | None
    self.detach_state_between_calls: bool = True
    # Distinguishes a state the user restored on purpose (via ``set_state``)
    # from one that merely accumulated through forward passes or lazy
    # zero-init.  Only the former is protected against a silent batch-size
    # re-init in ``_maybe_init_state`` — the latter is free to auto-resize.
    self._state_user_set: bool = False
    # Per-configuration cache of compiled teacher-forced chunk scans, keyed by
    # ``(id(cell), chunk, dtype, device)``.  Populated lazily by
    # ``forward_stateless(compile=...)`` and dropped on pickle / deepcopy (it
    # holds a ``torch.compile`` closure over the live cell that would
    # otherwise close over stale layers on a copy — mirrors the forecast
    # engine's ``_flat_step_cache`` hygiene in ``ESNModel``).
    self._compiled_scan_cache: dict[
        tuple[int, int, torch.dtype, torch.device], _ChunkScanFn
    ] = {}

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 (batch, timesteps, features).

TYPE: list[Tensor]

state

Initial reservoir state, shape (batch, ...) as produced by self.cell.init_state.

TYPE: Tensor

compile

Opt-in compiled/chunked engine for the teacher-forced sequence loop (warmup, ESNTrainer.fit forward, windowed_forecast re-sync). When True and the cell exposes the projected fast path (its project_inputs is not None), the recurrent-only cell.step update is unrolled DEFAULT_COMPILE_CHUNK steps at a time inside a torch.compile (mode="reduce-overhead", fullgraph=True) chunk driven chunk-by-chunk with cudagraph_mark_step_begin and state clones at boundaries — the teacher-forced analogue of the forecast engine (resdag.core._flat_inference). On the GPU this sheds the per-step launch/dispatch overhead that dominates the eager loop (~6-7x for a N=500/T=2000 warmup). The default (False) keeps the eager time loop below byte-for-byte unchanged.

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 torch < 2.10, or on any compilation failure (with a RuntimeWarning), so a correct result is always produced. Because chaotic reservoir dynamics under torch.compile need not be bit-exact with eager, the compiled output matches the eager output to a tight allclose (typically < 1e-5 max abs diff; closer for identity/linear activation) rather than bitwise.

TYPE: (bool, keyword - only) DEFAULT: False

RETURNS DESCRIPTION
outputs

Per-step outputs, shape (batch, timesteps, cell.output_size).

TYPE: Tensor

new_state

Final reservoir state after the last timestep.

TYPE: Tensor

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
def forward_stateless(
    self,
    inputs: list[torch.Tensor],
    state: torch.Tensor,
    *,
    compile: bool = False,
) -> tuple[torch.Tensor, torch.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.

    Parameters
    ----------
    inputs : list[torch.Tensor]
        Feedback tensor first, then at most one driving-input tensor, each
        of shape `(batch, timesteps, features)`.
    state : torch.Tensor
        Initial reservoir state, shape `(batch, ...)` as produced by
        `self.cell.init_state`.
    compile : bool, keyword-only, default=False
        Opt-in compiled/chunked engine for the teacher-forced sequence loop
        (warmup, `ESNTrainer.fit` forward, `windowed_forecast` re-sync).
        When `True` and the cell exposes the projected fast path (its
        `project_inputs` is not `None`), the recurrent-only `cell.step`
        update is unrolled `DEFAULT_COMPILE_CHUNK` steps at a time inside a
        `torch.compile` (`mode="reduce-overhead"`, `fullgraph=True`)
        chunk driven chunk-by-chunk with `cudagraph_mark_step_begin` and
        state clones at boundaries — the teacher-forced analogue of the
        forecast engine (`resdag.core._flat_inference`).  On the GPU this
        sheds the per-step launch/dispatch overhead that dominates the eager
        loop (~6-7x for a `N=500`/`T=2000` warmup).  The default (`False`)
        keeps the eager time loop below byte-for-byte unchanged.

        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 `torch < 2.10`, or on any compilation failure
        (with a `RuntimeWarning`), so a correct result is always
        produced.  Because chaotic reservoir dynamics under `torch.compile`
        need not be bit-exact with eager, the compiled output matches the
        eager output to a tight `allclose` (typically `< 1e-5` max abs
        diff; closer for identity/linear activation) rather than bitwise.

    Returns
    -------
    outputs : torch.Tensor
        Per-step outputs, shape `(batch, timesteps, cell.output_size)`.
    new_state : torch.Tensor
        Final reservoir state after the last timestep.

    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.
    """
    feedback = inputs[0]
    seq_len = feedback.shape[1]

    # Fast path: cells that split their update into input-dependent and
    # state-dependent parts precompute the former for the whole sequence
    # in one batched matmul, leaving only the recurrent term in the loop.
    # Choosing the path is a per-cell static decision made once, outside
    # the loop, so the loop body itself stays branch-free.
    projected = self.cell.project_inputs(inputs)

    # Opt-in compiled/chunked scan.  Gated to the projected fast path and
    # inference-only (no grad required): otherwise the eager loop below runs
    # exactly as before, keeping the default path byte-for-byte unchanged.
    if (
        compile
        and projected is not None
        and seq_len > 0
        and self._compile_eligible(projected, state)
    ):
        compiled = self._maybe_compiled_scan(projected, state)
        if compiled is not None:
            return self._run_compiled_scan(compiled, projected, state)

    outputs: list[torch.Tensor] = []
    if projected is not None:
        for t in range(seq_len):
            output, state = self.cell.step(projected[:, t, :], state)
            outputs.append(output)
    else:
        for t in range(seq_len):
            inputs_t = [stream[:, t, :] for stream in inputs]
            output, state = self.cell(inputs_t, state)
            outputs.append(output)

    if not outputs:
        # Degenerate empty sequence (T == 0): torch.stack rejects an empty
        # list, so return the (batch, 0, output_size) tensor the previous
        # preallocating loop produced, with the input ``state`` untouched.
        empty = feedback.new_empty(feedback.shape[0], 0, self.cell.output_size)
        return empty, state

    return torch.stack(outputs, dim=1), state

step_stateless

step_stateless(inputs: list[Tensor], state: Tensor) -> tuple[Tensor, Tensor]

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 (batch, features).

TYPE: list[Tensor]

state

Current reservoir state, shape (batch, ...) as produced by self.cell.init_state.

TYPE: Tensor

RETURNS DESCRIPTION
output

Per-step output, shape (batch, cell.output_size).

TYPE: Tensor

new_state

Updated reservoir state.

TYPE: Tensor

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
def step_stateless(
    self,
    inputs: list[torch.Tensor],
    state: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
    """
    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.

    Parameters
    ----------
    inputs : list[torch.Tensor]
        Feedback slice first, then at most one driving-input slice, each of
        shape `(batch, features)`.
    state : torch.Tensor
        Current reservoir state, shape `(batch, ...)` as produced by
        `self.cell.init_state`.

    Returns
    -------
    output : torch.Tensor
        Per-step output, shape `(batch, cell.output_size)`.
    new_state : torch.Tensor
        Updated reservoir state.

    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.
    """
    projected = self.cell.project_inputs(inputs)
    if projected is not None:
        return self.cell.step(projected, state)
    # ``nn.Module.__call__`` is typed ``Any``; unpack then return a tuple
    # literal so the declared ``tuple[Tensor, Tensor]`` is honoured (mirrors
    # ``forward_stateless``).
    output, new_state = self.cell(inputs, state)
    return output, new_state

forward

forward(feedback: Tensor, *driving_inputs: Tensor, compile: bool = False) -> Tensor

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 (batch, timesteps, feedback_size).

TYPE: Tensor

*driving_inputs

Optional driving input of shape (batch, timesteps, input_size). At most one driving input tensor is supported.

TYPE: Tensor DEFAULT: ()

compile

Route the teacher-forced sequence loop through the opt-in compiled/chunked engine. Forwarded verbatim to forward_stateless — see its compile parameter for the eligibility gating (projected fast path, inference-only) and the transparent eager fallback. The default (False) is byte-for-byte identical to the historical eager path.

TYPE: (bool, keyword - only) DEFAULT: False

RETURNS DESCRIPTION
Tensor

Reservoir states for all timesteps, shape (batch, timesteps, cell.output_size).

RAISES DESCRIPTION
ValueError

If feedback is not 3-D, if more than one driving input is supplied, or if the driving input batch/sequence dimensions do not match feedback.

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
def forward(
    self,
    feedback: torch.Tensor,
    *driving_inputs: torch.Tensor,
    compile: bool = False,
) -> torch.Tensor:
    """
    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.

    Parameters
    ----------
    feedback : torch.Tensor
        Feedback signal of shape `(batch, timesteps, feedback_size)`.
    *driving_inputs : torch.Tensor
        Optional driving input of shape `(batch, timesteps, input_size)`.
        At most one driving input tensor is supported.
    compile : bool, keyword-only, default=False
        Route the teacher-forced sequence loop through the opt-in
        compiled/chunked engine.  Forwarded verbatim to
        `forward_stateless` — see its `compile` parameter for the
        eligibility gating (projected fast path, inference-only) and the
        transparent eager fallback.  The default (`False`) is byte-for-byte
        identical to the historical eager path.

    Returns
    -------
    torch.Tensor
        Reservoir states for all timesteps, shape
        `(batch, timesteps, cell.output_size)`.

    Raises
    ------
    ValueError
        If `feedback` is not 3-D, if more than one driving input is
        supplied, or if the driving input batch/sequence dimensions do not
        match `feedback`.

    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.
    """
    if feedback.dim() != 3:
        raise ValueError(f"Feedback must be 3D (B, T, F), got shape {feedback.shape}")

    batch_size, seq_len, _ = feedback.shape

    if len(driving_inputs) > 0:
        if len(driving_inputs) > 1:
            raise ValueError("Only one driving input tensor allowed")
        driving_input = driving_inputs[0]
        if driving_input.dim() != 3 or driving_input.shape[:2] != (batch_size, seq_len):
            raise ValueError(
                f"Driving input must match feedback dimensions. "
                f"Feedback: {feedback.shape}, Driving: {driving_input.shape}"
            )

    self._maybe_init_state(batch_size, feedback.device, feedback.dtype)
    assert self.state is not None  # guaranteed by _maybe_init_state; narrows for mypy

    outputs, new_state = self.forward_stateless(
        [feedback, *driving_inputs], self.state, compile=compile
    )

    # Truncated BPTT at call boundaries: gradients flow through the returned
    # states within this call, but the *stored* state must not keep the
    # graph alive — a later forward + backward would otherwise try to
    # backprop through this call's already-freed graph.  This data-dependent
    # ``grad_fn`` branch lives here, in the wrapper, never inside the pure
    # loop of ``forward_stateless``.
    if self.detach_state_between_calls and (
        torch.compiler.is_compiling() or new_state.grad_fn is not None
    ):
        new_state = new_state.detach()

    self.state = new_state
    # The stored state has now evolved one or more steps past whatever the
    # user restored; it is no longer the as-set tensor, so drop the
    # user-set protection — a subsequent batch-size change is back to the
    # ordinary auto-resize regime.
    self._state_user_set = False
    return outputs

reference_device_dtype

reference_device_dtype() -> tuple[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 cpu.

TYPE: device

dtype

Dtype of the cell's first floating-point tensor, or float32.

TYPE: dtype

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
def reference_device_dtype(self) -> tuple[torch.device, torch.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
    -------
    device : torch.device
        Device of the cell's first floating-point tensor, or `cpu`.
    dtype : torch.dtype
        Dtype of the cell's first floating-point tensor, or `float32`.
    """
    ref = next(
        (
            t
            for t in chain(self.cell.parameters(), self.cell.buffers())
            if t.is_floating_point()
        ),
        None,
    )
    device = ref.device if ref is not None else torch.device("cpu")
    dtype = ref.dtype if ref is not None else torch.float32
    return device, dtype

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 None, state is set to None and will be lazily initialized on the next forward pass.

TYPE: int DEFAULT: None

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
def reset_state(self, batch_size: int | None = None) -> None:
    """
    Reset internal state to zero.

    Parameters
    ----------
    batch_size : int, optional
        If provided, initialize state with this batch size using the
        cell's device and dtype.  If `None`, state is set to `None`
        and will be lazily initialized on the next forward pass.

    Examples
    --------
    >>> layer.reset_state()          # Lazy initialization
    >>> layer.reset_state(batch_size=4)  # Explicit zero state
    """
    if batch_size is not None:
        if self.state is not None:
            device, dtype = self.state.device, self.state.dtype
        else:
            device, dtype = self.reference_device_dtype()
        self.state = self.cell.init_state(batch_size, device, dtype)
    else:
        self.state = None
    # A reset (zeros or back-to-None) is a deliberate opt-in to automatic
    # batch-size re-initialisation: drop any user-set protection.
    self._state_user_set = False

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 None if not yet initialized. The layout is cell-defined: 2-D (batch, cell.state_size) for resdag.layers.cells.esn_cell.ESNCell, 3-D (batch, cell.state_size, input_dim) delay buffer for resdag.layers.cells.ngrc_cell.NGCell.

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
def get_state(self) -> torch.Tensor | None:
    """
    Get a copy of the current internal state.

    Returns
    -------
    torch.Tensor or None
        Clone of the current state tensor, or `None` if not yet
        initialized.  The layout is cell-defined: 2-D
        `(batch, cell.state_size)` for
        `resdag.layers.cells.esn_cell.ESNCell`, 3-D
        `(batch, cell.state_size, input_dim)` delay buffer for
        `resdag.layers.cells.ngrc_cell.NGCell`.

    Examples
    --------
    >>> state = layer.get_state()
    >>> if state is not None:
    ...     print(f"State shape: {state.shape}")
    """
    return self.state.clone() if self.state is not None else None

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 (shape[0]) becomes the required batch size of the next forward pass.

TYPE: Tensor

RAISES DESCRIPTION
ValueError

If the cell's ReservoirCell.validate_state rejects the tensor. The error includes the cell class name and the offending shape.

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
def set_state(self, state: torch.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).

    Parameters
    ----------
    state : torch.Tensor
        New state tensor.  Its batch size (`shape[0]`) becomes the
        required batch size of the next forward pass.

    Raises
    ------
    ValueError
        If the cell's `ReservoirCell.validate_state` rejects the
        tensor.  The error includes the cell class name and the
        offending shape.

    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
    """
    try:
        self.cell.validate_state(state)
    except ValueError as exc:
        # Re-raise with a richer message including a recovery hint.
        raise ValueError(
            f"{type(self).__name__}.set_state failed: {exc}. "
            f"Tip: call reset_state(batch_size=...) before set_state() "
            f"to materialise an empty state of the expected layout."
        ) from None
    # Honour the truncated-BPTT contract on restore, just as ``forward``
    # does for the evolved state (see lines around the cross-call detach
    # there): a restored state is a fresh initial condition by default, so
    # under ``detach_state_between_calls`` strip any incoming ``grad_fn``
    # before storing it — otherwise restoring a graph-bearing tensor leaks
    # an autograd graph across calls (#146).  ``clone`` always runs so the
    # stored state is an independent copy regardless of the detach choice.
    if self.detach_state_between_calls and state.grad_fn is not None:
        self.state = state.detach().clone()
    else:
        self.state = state.clone()
    # Mark this as a deliberate restore: a later forward at a mismatched
    # batch size must raise rather than silently zero-reinit (see #145).
    self._state_user_set = True

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 device / dtype kwargs when given, otherwise the cell's first floating-point parameter/buffer (falling back to CPU/float32).

TYPE: int DEFAULT: None

device

Target device when lazily initialising. Ignored if the state is already initialised.

TYPE: device DEFAULT: None

dtype

Target dtype when lazily initialising. Ignored if the state is already initialised.

TYPE: dtype DEFAULT: None

RAISES DESCRIPTION
RuntimeError

If the state has not been initialised and batch_size is not provided.

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
def set_random_state(
    self,
    batch_size: int | None = None,
    device: torch.device | None = None,
    dtype: torch.dtype | None = None,
) -> None:
    """
    Set the internal state to random (standard-normal) values.

    Parameters
    ----------
    batch_size : int, optional
        If provided, lazily initialise the state with this batch size
        before filling it with random values.  Uses `device` / `dtype`
        kwargs when given, otherwise the cell's first floating-point
        parameter/buffer (falling back to CPU/float32).
    device : torch.device, optional
        Target device when lazily initialising.  Ignored if the state is
        already initialised.
    dtype : torch.dtype, optional
        Target dtype when lazily initialising.  Ignored if the state is
        already initialised.

    Raises
    ------
    RuntimeError
        If the state has not been initialised and `batch_size` is not
        provided.

    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()
    """
    if self.state is None:
        if batch_size is None:
            raise RuntimeError(
                "Reservoir state is not initialised. "
                "Pass batch_size= to initialise it before randomising."
            )
        self.reset_state(batch_size=batch_size)
        # ``reset_state(batch_size=...)`` always assigns a real tensor here
        # (batch_size is non-None past the guard above); narrows for mypy.
        assert self.state is not None
        # ``reset_state`` honours device/dtype of existing state or cell;
        # apply overrides if explicitly requested.
        if device is not None or dtype is not None:
            self.state = self.state.to(device=device, dtype=dtype)
    # State is non-None on both branches: either just initialised above or
    # already non-None at method entry.
    assert self.state is not None
    self.state = torch.randn_like(self.state)

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

k

Number of delay taps (including current input).

TYPE: int DEFAULT: 2

s

Spacing between delay taps, in timesteps.

TYPE: int DEFAULT: 1

p

Polynomial degree for nonlinear feature construction. By default (cumulative=False) only monomials of exactly degree p are emitted; lower-order cross terms (degrees 2, ..., p-1) are excluded. With cumulative=True every monomial of degree up to p is emitted (the "degree up to p" / full polynomial basis used by many NVAR implementations). When p == 1 and include_linear is True the nonlinear block is omitted, because the degree-1 monomials are identical to the linear features (see resdag.layers.cells.ngrc_cell.NGCell).

TYPE: int DEFAULT: 2

cumulative

Degree convention for the nonlinear block. False keeps only exact-degree-p monomials (default, unchanged behaviour); True includes all monomials of every degree up to p.

TYPE: bool DEFAULT: False

include_constant

Whether to prepend a constant 1.0 to the feature vector.

TYPE: bool DEFAULT: True

include_linear

Whether to include the linear delay-embedded features in the output.

TYPE: bool DEFAULT: True

ATTRIBUTE DESCRIPTION
cell

The inner single-step cell.

TYPE: NGCell

state

Current delay buffer of shape (batch, state_size, input_dim), or None if not yet initialized.

TYPE: Tensor or None

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
def __init__(
    self,
    input_dim: int,
    k: int = 2,
    s: int = 1,
    p: int = 2,
    cumulative: bool = False,
    include_constant: bool = True,
    include_linear: bool = True,
) -> None:
    cell = NGCell(
        input_dim=input_dim,
        k=k,
        s=s,
        p=p,
        cumulative=cumulative,
        include_constant=include_constant,
        include_linear=include_linear,
    )
    super().__init__(cell)

input_dim property

input_dim: int

Dimensionality of each input vector.

feature_dim property

feature_dim: int

Total dimension of the output feature vector.

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

inputs[0] is the input sequence of shape (batch, timesteps, input_dim). NG-RC has no driving inputs; forward rejects them before reaching this method, so only inputs[0] is consumed.

TYPE: list[Tensor]

state

Incoming delay buffer of shape (batch, state_size, input_dim).

TYPE: Tensor

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: bool DEFAULT: False

RETURNS DESCRIPTION
outputs

NG-RC features for all timesteps, shape (batch, timesteps, feature_dim).

TYPE: Tensor

new_state

Updated delay buffer of shape (batch, state_size, input_dim).

TYPE: Tensor

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
def forward_stateless(
    self,
    inputs: list[torch.Tensor],
    state: torch.Tensor,
    *,
    compile: bool = False,
) -> tuple[torch.Tensor, torch.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.

    Parameters
    ----------
    inputs : list[torch.Tensor]
        `inputs[0]` is the input sequence of shape
        `(batch, timesteps, input_dim)`.  NG-RC has no driving inputs;
        `forward` rejects them before reaching this method, so only
        `inputs[0]` is consumed.
    state : torch.Tensor
        Incoming delay buffer of shape `(batch, state_size, input_dim)`.
    compile : bool, default=False
        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.

    Returns
    -------
    outputs : torch.Tensor
        NG-RC features for all timesteps, shape
        `(batch, timesteps, feature_dim)`.
    new_state : torch.Tensor
        Updated delay buffer of shape `(batch, state_size, input_dim)`.
    """
    cell = cast(NGCell, self.cell)  # narrow from Tensor | Module for the type checker
    if len(inputs) != 1:
        raise ValueError("NGReservoirLayer does not accept driving inputs")
    return cell.forward_sequence(inputs[0], state)

forward

forward(feedback: Tensor, *driving_inputs: Tensor, compile: bool = False) -> Tensor

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 (batch, timesteps, input_dim).

TYPE: Tensor

*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 ValueError rather than silently discarding them and producing a misconfigured-but-running model.

TYPE: Tensor DEFAULT: ()

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: bool DEFAULT: False

RETURNS DESCRIPTION
Tensor

NG-RC features for all timesteps, shape (batch, timesteps, feature_dim).

RAISES DESCRIPTION
ValueError

If feedback is not 3-D, if any driving_inputs are passed, or if feedback's feature dimension does not equal input_dim.

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
def forward(
    self,
    feedback: torch.Tensor,
    *driving_inputs: torch.Tensor,
    compile: bool = False,
) -> torch.Tensor:
    """
    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.

    Parameters
    ----------
    feedback : torch.Tensor
        Input sequence of shape `(batch, timesteps, input_dim)`.
    *driving_inputs : torch.Tensor
        **Rejected.** NG-RC is a weightless feedforward feature map with no
        input weight matrix, so it cannot consume driving inputs.  Passing
        any raises `ValueError` rather than silently discarding them
        and producing a misconfigured-but-running model.
    compile : bool, default=False
        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.

    Returns
    -------
    torch.Tensor
        NG-RC features for all timesteps, shape
        `(batch, timesteps, feature_dim)`.

    Raises
    ------
    ValueError
        If `feedback` is not 3-D, if any `driving_inputs` are passed, or
        if `feedback`'s feature dimension does not equal
        `input_dim`.

    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).
    """
    if feedback.dim() != 3:
        raise ValueError(f"Feedback must be 3D (B, T, F), got shape {feedback.shape}")

    if driving_inputs:
        raise ValueError(
            f"NGReservoirLayer is a weightless feedforward feature map and does not "
            f"accept driving inputs, but {len(driving_inputs)} were passed. "
            f"NG-RC has no input weight matrix to consume them; wire only the "
            f"feedback sequence (shape (batch, timesteps, input_dim={self.input_dim})) "
            f"into this layer."
        )

    batch_size = feedback.shape[0]
    self._maybe_init_state(batch_size, feedback.device, feedback.dtype)

    # mypy: state is guaranteed non-None after _maybe_init_state.
    # driving_inputs are rejected above, so only the feedback stream is
    # threaded through the stateless feature map.
    assert self.state is not None
    outputs, new_state = self.forward_stateless([feedback], self.state)

    # Truncated BPTT at call boundaries (mirrors BaseReservoirLayer.forward):
    # gradients flow through the returned features within this call, but the
    # stored state must not keep the graph alive for a later forward+backward.
    # The data-dependent ``grad_fn`` branch lives here, never inside the pure
    # ``forward_stateless``.
    if self.detach_state_between_calls and new_state.grad_fn is not None:
        new_state = new_state.detach()

    self.state = new_state
    self._state_user_set = False
    return outputs

NGReservoir

NGReservoir(*args: Any, **kwargs: Any)

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
def __init__(self, *args: Any, **kwargs: Any) -> None:
    warnings.warn(
        "NGReservoir is deprecated and will be removed in a future release; "
        "use NGReservoirLayer instead.",
        DeprecationWarning,
        stacklevel=2,
    )
    super().__init__(*args, **kwargs)

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:

\[ 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} \]

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

feedback_size

Dimension of the feedback signal. Required.

TYPE: int

beta

Proximity to the edge of stability in \((0, 1]\) (see ES2NCell). A live knob: layer.beta = ... takes effect on the next forward.

TYPE: float DEFAULT: 0.9

input_size

Dimension of a driving input. None builds a feedback-only layer.

TYPE: int DEFAULT: None

spectral_radius

Target spectral radius for the recurrent matrix W_r.

TYPE: float DEFAULT: None

bias

Whether to include a bias term.

TYPE: bool DEFAULT: True

bias_scaling

Scale of the random bias (uniform(-bias_scaling, bias_scaling)).

TYPE: float DEFAULT: 1.0

activation

Activation for the nonlinear branch.

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

orthogonal_scaling

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

TYPE: float DEFAULT: 1.0

trainable

If True, reservoir weights are trainable via backpropagation. The orthogonal skip stays a frozen buffer regardless.

TYPE: bool DEFAULT: False

feedback_initializer

Same accepted forms as resdag.layers.ESNLayer.

TYPE: spec DEFAULT: None

input_initializer

Same accepted forms as resdag.layers.ESNLayer.

TYPE: spec DEFAULT: None

topology

Same accepted forms as resdag.layers.ESNLayer.

TYPE: spec DEFAULT: None

seed

Reproducibility seed fixing the recurrent, feedback, input, bias, and orthogonal-skip draws (the skip is drawn on an independent, deterministic sub-stream).

TYPE: int or Generator DEFAULT: None

recurrent_initializer

First-class alias for topology. Supply one spelling only. Names, tuples, callables and registered initializer objects are accepted.

TYPE: spec DEFAULT: None

bias_initializer

Input/feedback initializer grammar applied to a (1, reservoir_size) view of the bias. Requires bias=True; overrides bias_scaling.

TYPE: spec DEFAULT: None

initial_state_initializer

Initializes a persistent (1, cell.state_size) reset template once. Each batch example receives an independent copy at reset. Zero by default.

TYPE: spec DEFAULT: None

device

Initial parameter location. Metal construction initializes on CPU before transferring to support initialization operations across backends.

TYPE: device or str DEFAULT: None

dtype

Floating precision used during initialization, not only after conversion.

TYPE: dtype DEFAULT: None

ATTRIBUTE DESCRIPTION
state

Current reservoir state of shape (batch, reservoir_size), or None before the first forward.

TYPE: Tensor or None

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
def __init__(
    self,
    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: torch.device | str | None = None,
    dtype: torch.dtype | None = None,
) -> None:
    cell = ES2NCell(
        reservoir_size=reservoir_size,
        feedback_size=feedback_size,
        beta=beta,
        input_size=input_size,
        spectral_radius=spectral_radius,
        bias=bias,
        bias_scaling=bias_scaling,
        activation=activation,
        orthogonal_scaling=orthogonal_scaling,
        trainable=trainable,
        feedback_initializer=feedback_initializer,
        input_initializer=input_initializer,
        topology=topology,
        seed=seed,
        recurrent_initializer=recurrent_initializer,
        bias_initializer=bias_initializer,
        initial_state_initializer=initial_state_initializer,
        device=device,
        dtype=dtype,
    )
    super().__init__(cell)

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:

\[ x_t = \alpha\,O\,x_{t-1} + \beta\,\phi(W_r x_{t-1} + W_{fb} x_{fb,t} + W_{in} u_t + b) \]

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

feedback_size

Dimension of the feedback signal. Required.

TYPE: int

alpha

Scaling of the orthogonal skip (residual) branch. A live knob: layer.alpha = ... takes effect on the next forward.

TYPE: float DEFAULT: 0.5

beta

Scaling of the nonlinear branch. A live knob.

TYPE: float DEFAULT: 0.9

input_size

Dimension of a driving input. None builds a feedback-only layer.

TYPE: int DEFAULT: None

spectral_radius

Target spectral radius for the recurrent matrix W_r.

TYPE: float DEFAULT: None

bias

Whether to include a bias term.

TYPE: bool DEFAULT: True

bias_scaling

Scale of the random bias (uniform(-bias_scaling, bias_scaling)).

TYPE: float DEFAULT: 1.0

activation

Activation for the nonlinear branch.

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

orthogonal_scaling

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

TYPE: float DEFAULT: 1.0

trainable

If True, reservoir weights are trainable via backpropagation. The orthogonal skip stays a frozen buffer regardless.

TYPE: bool DEFAULT: False

feedback_initializer

Same accepted forms as resdag.layers.ESNLayer.

TYPE: spec DEFAULT: None

input_initializer

Same accepted forms as resdag.layers.ESNLayer.

TYPE: spec DEFAULT: None

topology

Same accepted forms as resdag.layers.ESNLayer.

TYPE: spec DEFAULT: None

seed

Reproducibility seed fixing the recurrent, feedback, input, bias, and orthogonal-skip draws (the skip is drawn on an independent, deterministic sub-stream).

TYPE: int or Generator DEFAULT: None

recurrent_initializer

First-class alias for topology. Supply one spelling only. Names, tuples, callables and registered initializer objects are accepted.

TYPE: spec DEFAULT: None

bias_initializer

Input/feedback initializer grammar applied to a (1, reservoir_size) view of the bias. Requires bias=True; overrides bias_scaling.

TYPE: spec DEFAULT: None

initial_state_initializer

Initializes a persistent (1, cell.state_size) reset template once. Each batch example receives an independent copy at reset. Zero by default.

TYPE: spec DEFAULT: None

device

Initial parameter location. Metal construction initializes on CPU before transferring to support initialization operations across backends.

TYPE: device or str DEFAULT: None

dtype

Floating precision used during initialization, not only after conversion.

TYPE: dtype DEFAULT: None

ATTRIBUTE DESCRIPTION
state

Current reservoir state of shape (batch, reservoir_size), or None before the first forward.

TYPE: Tensor or None

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
def __init__(
    self,
    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: torch.device | str | None = None,
    dtype: torch.dtype | None = None,
) -> None:
    cell = ResESNCell(
        reservoir_size=reservoir_size,
        feedback_size=feedback_size,
        alpha=alpha,
        beta=beta,
        input_size=input_size,
        spectral_radius=spectral_radius,
        bias=bias,
        bias_scaling=bias_scaling,
        activation=activation,
        orthogonal_scaling=orthogonal_scaling,
        trainable=trainable,
        feedback_initializer=feedback_initializer,
        input_initializer=input_initializer,
        topology=topology,
        seed=seed,
        recurrent_initializer=recurrent_initializer,
        bias_initializer=bias_initializer,
        initial_state_initializer=initial_state_initializer,
        device=device,
        dtype=dtype,
    )
    super().__init__(cell)

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

feedback_size

Dimension of the feedback signal. Required.

TYPE: int

input_size

Dimension of an optional driving input. None (or 0) builds a feedback-only reservoir.

TYPE: int DEFAULT: None

spectral_radius

Target spectral radius for the recurrent candidate weight. Controls the echo of past state through the candidate path. None applies no scaling.

TYPE: float DEFAULT: None

bias

Whether to include the gate biases.

TYPE: bool DEFAULT: True

bias_scaling

Scale of the random candidate bias b_h. The update-gate bias is the constant retention bias (see update_gate_bias), not randomised.

TYPE: float DEFAULT: 1.0

update_gate_bias

Constant update-gate bias biasing z toward retention (z≈0.88 at 2.0). Keeps a frozen gated reservoir from washing out its memory.

TYPE: float DEFAULT: 2.0

activation

Candidate nonlinearity (LiGRU default is "relu").

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

gate_activation

Update-gate nonlinearity; "sigmoid" keeps z a valid gate.

TYPE: (sigmoid, ...) DEFAULT: 'sigmoid'

trainable

If True, all weights are trainable via backpropagation. A frozen gated reservoir often underperforms an ESN — gated reservoirs are usually best used with trainable=True.

TYPE: bool DEFAULT: False

feedback_initializer

Initializer for the feedback drive weights. Same accepted forms as resdag.layers.ESNLayer.

TYPE: str, callable, tuple, or InputFeedbackInitializer DEFAULT: None

input_initializer

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

TYPE: str, callable, tuple, or InputFeedbackInitializer DEFAULT: None

topology

Structure of the recurrent candidate weight. The update-gate recurrent weight is always dense-random.

TYPE: str, callable, tuple, or TopologyInitializer DEFAULT: None

seed

Reproducibility seed fixing the entire reservoir.

TYPE: int or Generator DEFAULT: None

recurrent_initializer

First-class alias for topology. Supply one spelling only. Names, tuples, callables and registered initializer objects are accepted.

TYPE: spec DEFAULT: None

bias_initializer

Input/feedback initializer grammar applied to a (1, reservoir_size) view of the bias. Requires bias=True; overrides bias_scaling.

TYPE: spec DEFAULT: None

initial_state_initializer

Initializes a persistent (1, cell.state_size) reset template once. Each batch example receives an independent copy at reset. Zero by default.

TYPE: spec DEFAULT: None

device

Initial parameter location. Metal construction initializes on CPU before transferring to support initialization operations across backends.

TYPE: device or str DEFAULT: None

dtype

Floating precision used during initialization, not only after conversion.

TYPE: dtype DEFAULT: None

gate_recurrent_initializer

Separate recurrent gate matrix. Defaults to small dense random weights.

TYPE: spec DEFAULT: None

gate_spectral_radius

Outer radius target for the gate recurrence, respecting its scaling policy.

TYPE: float DEFAULT: None

gate_feedback_initializer

Separate gate projections. Omitted projections share candidate weights. A driver gate initializer requires input_size.

TYPE: spec DEFAULT: None

gate_input_initializer

Separate gate projections. Omitted projections share candidate weights. A driver gate initializer requires input_size.

TYPE: spec DEFAULT: None

gate_bias_initializer

Gate-bias initializer on (1, reservoir_size); overrides update_gate_bias. Requires bias=True.

TYPE: spec DEFAULT: None

ATTRIBUTE DESCRIPTION
state

Current packed reservoir state of shape (batch, reservoir_size), or None if not yet initialized.

TYPE: Tensor or None

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
def __init__(
    self,
    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: torch.device | str | None = None,
    dtype: torch.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,
) -> None:
    cell = GatedReservoirCell(
        reservoir_size=reservoir_size,
        feedback_size=feedback_size,
        input_size=input_size,
        spectral_radius=spectral_radius,
        bias=bias,
        bias_scaling=bias_scaling,
        update_gate_bias=update_gate_bias,
        activation=activation,
        gate_activation=gate_activation,
        trainable=trainable,
        feedback_initializer=feedback_initializer,
        input_initializer=input_initializer,
        topology=topology,
        seed=seed,
        recurrent_initializer=recurrent_initializer,
        bias_initializer=bias_initializer,
        initial_state_initializer=initial_state_initializer,
        device=device,
        dtype=dtype,
        gate_recurrent_initializer=gate_recurrent_initializer,
        gate_feedback_initializer=gate_feedback_initializer,
        gate_input_initializer=gate_input_initializer,
        gate_bias_initializer=gate_bias_initializer,
        gate_spectral_radius=gate_spectral_radius,
    )
    super().__init__(cell)

GatedReservoir

GatedReservoir(*args: Any, **kwargs: Any)

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
def __init__(self, *args: Any, **kwargs: Any) -> None:
    warnings.warn(
        "GatedReservoir is deprecated and will be removed in a future release; "
        "use GatedReservoirLayer instead.",
        DeprecationWarning,
        stacklevel=2,
    )
    super().__init__(*args, **kwargs)

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:

\[ h_t = h_{t-1} + \varepsilon\, \tanh\!\big((W_r - W_r^\top - \gamma I)\, h_{t-1} + W_{fb} x_{fb,t} + W_{in} u_t + b\big). \]

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

feedback_size

Dimension of the feedback signal. Required.

TYPE: int

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: float DEFAULT: 0.01

gamma

Diffusion coefficient \(\gamma \ge 0\). A live knob: layer.gamma = ... takes effect on the next forward.

TYPE: float DEFAULT: 0.01

input_size

Dimension of a driving input. None builds a feedback-only layer.

TYPE: int DEFAULT: None

spectral_radius

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

TYPE: float DEFAULT: None

bias

Whether to include a bias term.

TYPE: bool DEFAULT: True

bias_scaling

Scale of the random bias (uniform(-bias_scaling, bias_scaling)).

TYPE: float DEFAULT: 1.0

activation

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

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

substeps

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

TYPE: int DEFAULT: 1

solver

Integration scheme (see EuSNCell).

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

trainable

If True, reservoir weights are trainable via backpropagation.

TYPE: bool DEFAULT: False

feedback_initializer

Same accepted forms as resdag.layers.ESNLayer. topology defaults (None) to a dense random W_r; the cell antisymmetrizes it on the fly.

TYPE: spec DEFAULT: None

input_initializer

Same accepted forms as resdag.layers.ESNLayer. topology defaults (None) to a dense random W_r; the cell antisymmetrizes it on the fly.

TYPE: spec DEFAULT: None

topology

Same accepted forms as resdag.layers.ESNLayer. topology defaults (None) to a dense random W_r; the cell antisymmetrizes it on the fly.

TYPE: spec DEFAULT: None

seed

Reproducibility seed fixing the recurrent, feedback, input and bias draws.

TYPE: int or Generator DEFAULT: None

recurrent_initializer

First-class alias for topology. Supply one spelling only. Names, tuples, callables and registered initializer objects are accepted.

TYPE: spec DEFAULT: None

bias_initializer

Input/feedback initializer grammar applied to a (1, reservoir_size) view of the bias. Requires bias=True; overrides bias_scaling.

TYPE: spec DEFAULT: None

initial_state_initializer

Initializes a persistent (1, cell.state_size) reset template once. Each batch example receives an independent copy at reset. Zero by default.

TYPE: spec DEFAULT: None

device

Initial parameter location. Metal construction initializes on CPU before transferring to support initialization operations across backends.

TYPE: device or str DEFAULT: None

dtype

Floating precision used during initialization, not only after conversion.

TYPE: dtype DEFAULT: None

ATTRIBUTE DESCRIPTION
state

Current reservoir state of shape (batch, reservoir_size), or None before the first forward.

TYPE: Tensor or None

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
def __init__(
    self,
    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-6,
    atol: float = 1e-8,
    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: torch.device | str | None = None,
    dtype: torch.dtype | None = None,
) -> None:
    cell = EuSNCell(
        reservoir_size=reservoir_size,
        feedback_size=feedback_size,
        epsilon=epsilon,
        gamma=gamma,
        input_size=input_size,
        spectral_radius=spectral_radius,
        bias=bias,
        bias_scaling=bias_scaling,
        activation=activation,
        substeps=substeps,
        solver=solver,
        torchdiffeq_method=torchdiffeq_method,
        rtol=rtol,
        atol=atol,
        trainable=trainable,
        feedback_initializer=feedback_initializer,
        input_initializer=input_initializer,
        topology=topology,
        seed=seed,
        recurrent_initializer=recurrent_initializer,
        bias_initializer=bias_initializer,
        initial_state_initializer=initial_state_initializer,
        device=device,
        dtype=dtype,
    )
    super().__init__(cell)

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

feedback_size

Dimension of the feedback / driving signal. Required.

TYPE: int

input_size

Dimension of an optional second driving input. None (or 0) builds a single-input reservoir.

TYPE: int DEFAULT: None

tau_mem

Membrane time constant \(\tau_\text{mem}\).

TYPE: float DEFAULT: 20.0

tau_syn

Synaptic time constant \(\tau_\text{syn}\) (CuBa-LIF only).

TYPE: float DEFAULT: 10.0

dt

Integration timestep.

TYPE: float DEFAULT: 1.0

synaptic_current

If True, use the second-order current-based LIF (CuBa-LIF).

TYPE: bool DEFAULT: False

v_threshold

Firing threshold.

TYPE: float DEFAULT: 1.0

reset

Membrane reset on a spike.

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

surrogate_beta

Fast-sigmoid surrogate slope for the straight-through spike gradient.

TYPE: float DEFAULT: 10.0

trace_decay

Decay of the low-pass readout trace.

TYPE: float DEFAULT: 0.9

output

Readable-output mode; 'trace' is the ridge-regressable default.

TYPE: (trace, voltage, spikes) DEFAULT: 'trace'

spectral_radius

Target spectral radius for the recurrent spike-coupling weight W_rec.

TYPE: float DEFAULT: None

bias

Whether to include a bias current.

TYPE: bool DEFAULT: True

bias_scaling

Scale of the random bias (uniform(-bias_scaling, bias_scaling)).

TYPE: float DEFAULT: 1.0

trainable

If True, all weights are trainable via the surrogate spike gradient.

TYPE: bool DEFAULT: False

feedback_initializer

Same accepted forms as resdag.layers.ESNLayer.

TYPE: spec DEFAULT: None

input_initializer

Same accepted forms as resdag.layers.ESNLayer.

TYPE: spec DEFAULT: None

topology

Same accepted forms as resdag.layers.ESNLayer.

TYPE: spec DEFAULT: None

seed

Reproducibility seed fixing the recurrent, feedback, input and bias draws.

TYPE: int or Generator DEFAULT: None

recurrent_initializer

First-class alias for topology. Supply one spelling only. Names, tuples, callables and registered initializer objects are accepted.

TYPE: spec DEFAULT: None

bias_initializer

Input/feedback initializer grammar applied to a (1, reservoir_size) view of the bias. Requires bias=True; overrides bias_scaling.

TYPE: spec DEFAULT: None

initial_state_initializer

Initializes a persistent (1, cell.state_size) reset template once. Each batch example receives an independent copy at reset. Zero by default.

TYPE: spec DEFAULT: None

device

Initial parameter location. Metal construction initializes on CPU before transferring to support initialization operations across backends.

TYPE: device or str DEFAULT: None

dtype

Floating precision used during initialization, not only after conversion.

TYPE: dtype DEFAULT: None

ATTRIBUTE DESCRIPTION
state

Current packed reservoir state of shape (batch, cell.state_size), or None before the first forward.

TYPE: Tensor or None

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
def __init__(
    self,
    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: torch.device | str | None = None,
    dtype: torch.dtype | None = None,
) -> None:
    cell = LIFCell(
        reservoir_size=reservoir_size,
        feedback_size=feedback_size,
        input_size=input_size,
        tau_mem=tau_mem,
        tau_syn=tau_syn,
        dt=dt,
        synaptic_current=synaptic_current,
        v_threshold=v_threshold,
        reset=reset,
        surrogate_beta=surrogate_beta,
        trace_decay=trace_decay,
        output=output,
        spectral_radius=spectral_radius,
        bias=bias,
        bias_scaling=bias_scaling,
        trainable=trainable,
        feedback_initializer=feedback_initializer,
        input_initializer=input_initializer,
        topology=topology,
        seed=seed,
        recurrent_initializer=recurrent_initializer,
        bias_initializer=bias_initializer,
        initial_state_initializer=initial_state_initializer,
        device=device,
        dtype=dtype,
    )
    super().__init__(cell)

LIFReservoir

LIFReservoir(*args: Any, **kwargs: Any)

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
def __init__(self, *args: Any, **kwargs: Any) -> None:
    warnings.warn(
        "LIFReservoir is deprecated and will be removed in a future release; "
        "use LIFReservoirLayer instead.",
        DeprecationWarning,
        stacklevel=2,
    )
    super().__init__(*args, **kwargs)

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
def __init__(
    self,
    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: torch.device | str | None = None,
    dtype: torch.dtype | None = None,
) -> None:
    super().__init__(
        CoRNNCell(
            reservoir_size,
            feedback_size,
            input_size,
            dt=dt,
            gamma=gamma,
            epsilon=epsilon,
            recurrent_initializer=recurrent_initializer,
            velocity_initializer=velocity_initializer,
            topology=topology,
            spectral_radius=spectral_radius,
            feedback_initializer=feedback_initializer,
            input_initializer=input_initializer,
            bias=bias,
            bias_scaling=bias_scaling,
            trainable=trainable,
            seed=seed,
            device=device,
            dtype=dtype,
        )
    )

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
def __init__(
    self,
    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: torch.device | str | None = None,
    dtype: torch.dtype | None = None,
) -> None:
    super().__init__(
        LegendreDelayCell(
            order,
            feedback_size,
            input_size,
            theta=theta,
            dt=dt,
            memory_channels=memory_channels,
            feedback_initializer=feedback_initializer,
            input_initializer=input_initializer,
            trainable=trainable,
            seed=seed,
            device=device,
            dtype=dtype,
        )
    )

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
def __init__(
    self,
    cell: nn.GRUCell | nn.LSTMCell,
    feedback_size: int,
    input_size: int | None = None,
    *,
    trainable: bool = False,
) -> None:
    super().__init__(TorchRecurrentCell(cell, feedback_size, input_size, trainable=trainable))

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 (solver='cholesky') or LU (solver='solve') factorisation of the normal equations.

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 alpha=0.

PinvReadoutLayer

Least-squares readout via torch.linalg.lstsq / pinv with an rcond cutoff.

IncrementalRidgeReadoutLayer

Streaming ridge readout: partial_fit accumulates sufficient statistics chunk-by-chunk, finalize solves once. For the DataLoader / long-sequence path.

RLSReadout

True-online Recursive Least Squares readout with a forgetting factor: partial_fit refines the weights one sample at a time from a running inverse-correlation matrix. Tracks non-stationary targets (lambda < 1) and converges to ordinary least squares (lambda = 1).

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

out_features

Size of output features.

TYPE: int

bias

Whether to include a bias term.

TYPE: bool DEFAULT: True

name

Name for this readout layer. Used for identification in multi-readout architectures and by ESNTrainer.

TYPE: str DEFAULT: None

trainable

If True, weights are trainable via backpropagation. If False, weights are frozen (standard ESN behavior).

TYPE: bool DEFAULT: False

ATTRIBUTE DESCRIPTION
weight

Weight matrix of shape (out_features, in_features).

TYPE: Parameter

bias

Bias vector of shape (out_features,), or None if bias=False.

TYPE: Parameter or None

name

Name of this readout layer.

TYPE: str or None

is_fitted

True if fit() has been called successfully.

TYPE: bool

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
def __init__(
    self,
    in_features: int,
    out_features: int,
    bias: bool = True,
    name: str | None = None,
    trainable: bool = False,
) -> None:
    super().__init__(in_features, out_features, bias)

    self._name = name
    # ``is_fitted`` is stored as a registered (persistent) buffer so it
    # survives ``state_dict`` / ``load_state_dict`` round-trips. A plain
    # Python attribute would silently reset to ``False`` on reload, leaving
    # a model with fitted weights but ``is_fitted == False``.
    self.register_buffer("_is_fitted", torch.zeros((), dtype=torch.bool))
    # Plain Python mirror of the ``_is_fitted`` buffer. Reading the buffer
    # via ``.item()`` is a device->host sync on CUDA — cheap once, but
    # ruinous inside a per-step autoregressive forecast loop (and it also
    # graph-breaks ``torch.compile``). The mirror lets hot paths (e.g.
    # ``IncrementalRidgeReadoutLayer.forward``) check fittedness with a plain
    # attribute read and no sync. It is kept coherent with the buffer via
    # :meth:`_set_fitted` and re-derived from the buffer after every
    # ``load_state_dict`` (see :meth:`_load_from_state_dict`).
    self._fitted_flag: bool = False
    # Register a post-load hook so subclasses/instances loaded via
    # ``load_state_dict`` re-sync the Python mirror from the restored buffer.
    self.register_load_state_dict_post_hook(_sync_fitted_flag_post_hook)

    # ``trainable`` is a live property whose setter flips ``requires_grad_``
    # on every parameter (``weight``, ``bias``).  ``nn.Linear.__init__`` has
    # already created those parameters, so a single assignment both records
    # the flag and applies the freeze/unfreeze — no separate
    # ``_freeze_weights`` step is needed.
    self.trainable = trainable

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.

name property

name: str | None

str or None : Name of this readout layer.

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

forward(input: Tensor) -> Tensor

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 (B, F) or (B, T, F).

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Output tensor of shape (B, F_out) or (B, T, F_out).

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
def forward(self, input: torch.Tensor) -> torch.Tensor:
    """
    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.

    Parameters
    ----------
    input : torch.Tensor
        Input tensor of shape `(B, F)` or `(B, T, F)`.

    Returns
    -------
    torch.Tensor
        Output tensor of shape `(B, F_out)` or `(B, T, F_out)`.

    Raises
    ------
    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)
    """
    if input.dim() == 2:
        return super().forward(input)

    elif input.dim() == 3:
        batch_size, seq_len, features = input.shape
        input_reshaped = input.reshape(batch_size * seq_len, features)
        output_reshaped = super().forward(input_reshaped)
        output = output_reshaped.reshape(batch_size, seq_len, self.out_features)
        return output

    else:
        raise ValueError(
            f"ReadoutLayer expects 2D (B, F) or 3D (B, T, F) input, "
            f"got {input.dim()}D tensor with shape {input.shape}"
        )

fit

fit(states: Tensor, targets: Tensor) -> None

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 (B, T, F_in) or (N, F_in).

TYPE: Tensor

targets

Target outputs of shape (B, T, F_out) or (N, F_out).

TYPE: Tensor

RAISES DESCRIPTION
NotImplementedError

The base ReadoutLayer does not implement an algebraic solver; use a subclass such as CGReadoutLayer.

ValueError

If states and targets disagree on the sample dimension after flattening, if the state's feature dimension does not match self.in_features, if the target's feature dimension does not match self.out_features, or if states or targets contain non-finite (NaN or Inf) values.

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
@torch.no_grad()
def fit(
    self,
    states: torch.Tensor,
    targets: torch.Tensor,
) -> None:
    """
    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.

    Parameters
    ----------
    states : torch.Tensor
        Input states of shape `(B, T, F_in)` or `(N, F_in)`.
    targets : torch.Tensor
        Target outputs of shape `(B, T, F_out)` or `(N, F_out)`.

    Raises
    ------
    NotImplementedError
        The base `ReadoutLayer` does not implement an algebraic solver;
        use a subclass such as `CGReadoutLayer`.
    ValueError
        If `states` and `targets` disagree on the sample dimension
        after flattening, if the state's feature dimension does not match
        `self.in_features`, if the target's feature dimension does not
        match `self.out_features`, or if `states` or `targets`
        contain non-finite (NaN or Inf) values.

    Notes
    -----
    After `fit()` returns successfully, `is_fitted` is `True`.

    See Also
    --------
    CGReadoutLayer : Concrete implementation using Conjugate Gradient.
    """
    states, targets = self._prepare_fit_inputs(states, targets, "fit")

    coefs, intercept = self.solve(states, targets)

    self._copy_coefficients(coefs, intercept)
    self._set_fitted(True)

solve

solve(states: Tensor, targets: Tensor) -> tuple[Tensor, Tensor | None]

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 (N, in_features).

TYPE: Tensor

targets

Flattened targets of shape (N, out_features).

TYPE: Tensor

RETURNS DESCRIPTION
coefs

Coefficient matrix of shape (in_features, out_features). The base fit transposes this into the (out, in) layout expected by nn.Linear.

TYPE: Tensor

intercept

Bias vector of shape (out_features,), or None to leave the layer's bias untouched.

TYPE: Tensor or None

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
def solve(
    self,
    states: torch.Tensor,
    targets: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor | None]:
    """
    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.

    Parameters
    ----------
    states : torch.Tensor
        Flattened input states of shape `(N, in_features)`.
    targets : torch.Tensor
        Flattened targets of shape `(N, out_features)`.

    Returns
    -------
    coefs : torch.Tensor
        Coefficient matrix of shape `(in_features, out_features)`.
        The base `fit` transposes this into the `(out, in)` layout
        expected by `nn.Linear`.
    intercept : torch.Tensor or None
        Bias vector of shape `(out_features,)`, or `None` to leave
        the layer's bias untouched.

    Raises
    ------
    NotImplementedError
        The base class does not implement an algebraic solve.
    """
    raise NotImplementedError(
        "ReadoutLayer.solve() is not implemented in the base class. "
        "Use CGReadoutLayer for ridge regression fitting, or subclass "
        "ReadoutLayer and override solve()."
    )

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

TYPE: int

out_features

Input and output dimensions, as for ReadoutLayer.

TYPE: int

bias

Fit an unpenalized intercept by centering the training data.

TYPE: bool DEFAULT: True

name

Readout name used by custom graphs and training targets.

TYPE: str DEFAULT: None

trainable

Allow ordinary PyTorch gradients through the fitted linear layer. Algebraic fitting itself does not build a differentiation graph.

TYPE: bool DEFAULT: False

alpha

Finite nonnegative L2 penalty. The requested value is never inflated.

TYPE: float DEFAULT: 1e-6

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: ('auto', 'primal', 'dual', 'qr', 'svd') DEFAULT: "auto"

solve_dtype

Working precision: torch.float32 or torch.float64. By default CPU/CUDA use float64 and MPS first tries native float32. Parameters retain their normal PyTorch dtype and device.

TYPE: dtype DEFAULT: None

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

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 last_solve. False raises instead. A forced method stays the same across the bridge.

TYPE: bool DEFAULT: True

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
def __init__(
    self,
    in_features: int,
    out_features: int,
    bias: bool = True,
    name: str | None = None,
    trainable: bool = False,
    alpha: float = 1e-6,
    solver: Solver = "auto",
    solve_dtype: torch.dtype | None = None,
    rcond: float | None = None,
    cpu_fallback: bool = True,
) -> None:
    super().__init__(in_features, out_features, bias, name, trainable)
    self.alpha = alpha
    self.solver = solver
    self.solve_dtype = solve_dtype
    self.rcond = rcond
    self.cpu_fallback = cpu_fallback
    self.last_solve: ReadoutSolveReport | None = None
    self._validate_options()

solve

solve(states: Tensor, targets: Tensor) -> tuple[Tensor, Tensor | None]

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
def solve(
    self, states: torch.Tensor, targets: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor | None]:
    """Solve flattened training data and record the actual numerical path."""
    self._validate_options()
    reasons: list[str] = []
    device = states.device
    dtype = self.solve_dtype or (torch.float32 if device.type == "mps" else torch.float64)

    def bridge(reason: str) -> None:
        nonlocal device, dtype
        if not self.cpu_fallback:
            raise RuntimeError(
                f"AutoReadoutLayer needs a CPU solve: {reason}. "
                "Set cpu_fallback=True or choose a supported precision/solver."
            )
        reasons.append(reason)
        warnings.warn(
            f"AutoReadoutLayer: using CPU float64 fitting ({reason}); "
            f"fitted parameters remain on {states.device}.",
            RuntimeWarning,
            stacklevel=3,
        )
        device, dtype = torch.device("cpu"), torch.float64

    if device.type == "mps" and dtype == torch.float64:
        bridge("MPS does not support float64")

    problem: LeastSquaresProblem | None = None
    residuals: tuple[float, float] | None = None

    def prepare() -> tuple[torch.Tensor, torch.Tensor]:
        nonlocal problem, residuals
        residuals = None
        problem = build_least_squares_problem(
            states.to(device=device),
            targets.to(device=device),
            fit_intercept=self.bias is not None,
            use_float64=dtype == torch.float64,
            gram_dtype=dtype,
        )
        x, y = problem.X, problem.y
        if problem.fit_intercept:
            assert problem.x_mean is not None and problem.y_mean is not None
            x, y = x - problem.x_mean, y - problem.y_mean
        if not torch.isfinite(x).all() or not torch.isfinite(y).all():
            raise RuntimeError(
                "AutoReadoutLayer centering exceeded the working dtype range; rescale the data."
            )
        return x, y

    x, y = prepare()
    requested = self.solver
    method = requested
    condition, roundoff = math.inf, None
    if requested == "auto":
        method = "primal" if x.shape[0] >= x.shape[1] else "dual"
        if method == "dual" and self.alpha == 0:
            method = "svd"
    if method in ("primal", "dual"):
        try:
            try:
                coefs, condition, roundoff = self._gram_solve(x, y, dual=method == "dual")
            except NotImplementedError:
                if device.type == "cpu":
                    raise
                bridge(f"{device.type} does not implement a required {method} operation")
                x, y = prepare()
                coefs, condition, roundoff = self._gram_solve(x, y, dual=method == "dual")
            residuals = self._residuals(x, y, coefs)
            tol = math.sqrt(torch.finfo(dtype).eps)
            safe = math.isfinite(roundoff) and roundoff <= tol and residuals[0] <= tol
            if not safe:
                reason = f"{method} normal equations failed the precision/conditioning guard"
                if requested != "auto":
                    warnings.warn(
                        f"AutoReadoutLayer: forced {reason}.", RuntimeWarning, stacklevel=2
                    )
                else:
                    raise _UnsafeSolveError(reason)
        except (torch.linalg.LinAlgError, _UnsafeSolveError) as exc:
            if requested != "auto":
                raise RuntimeError(f"Forced {method} solve failed: {exc}") from exc
            reasons.append(str(exc))
            method = "qr" if x.shape[0] >= x.shape[1] else "svd"
    if method in ("qr", "svd"):
        # A decomposition replaces any rejected normal-equations coefficients.
        residuals = None
        if device.type == "mps":
            bridge(f"MPS {method} requires a stable CPU decomposition")
            x, y = prepare()
        try:
            solve_decomposition = self._qr_solve if method == "qr" else self._svd_solve
            try:
                coefs, condition = solve_decomposition(x, y)
            except NotImplementedError:
                if device.type == "cpu":
                    raise
                bridge(f"{device.type} does not implement a required {method} operation")
                x, y = prepare()
                coefs, condition = solve_decomposition(x, y)
        except (torch.linalg.LinAlgError, _UnsafeSolveError) as exc:
            if requested != "auto" or method == "svd":
                raise RuntimeError(f"{method} solve failed: {exc}") from exc
            reasons.append(str(exc))
            method = "svd"
            coefs, condition = self._svd_solve(x, y)
        roundoff = None
    if not torch.isfinite(coefs).all():
        raise RuntimeError(
            "AutoReadoutLayer produced non-finite coefficients; rescale the data."
        )
    # Reuse the admission diagnostics when the Gram solution is unchanged.
    if residuals is None:
        residuals = self._residuals(x, y, coefs)
    residual, prediction_residual = residuals
    precision_warning = None
    if (
        self.alpha > 0
        and method in ("qr", "svd")
        and math.sqrt(condition) * torch.finfo(dtype).eps > math.sqrt(torch.finfo(dtype).eps)
    ):
        precision_warning = (
            "The regularized design is severely ill-conditioned at the working precision. "
            "Fitted coefficients may be inaccurate even with small training/optimality "
            "residuals. Rescale features, choose stronger regularization explicitly, "
            "or use higher precision; alpha was not changed."
        )
        warnings.warn(f"AutoReadoutLayer: {precision_warning}", RuntimeWarning, stacklevel=2)
    assert problem is not None
    coefs_out, intercept = finalize_fit(problem, coefs)
    self.last_solve = ReadoutSolveReport(
        requested_solver=requested,
        solver=method,
        alpha=self.alpha,
        input_device=str(states.device),
        input_dtype=states.dtype,
        solve_device=str(device),
        solve_dtype=dtype,
        n_samples=x.shape[0],
        n_features=x.shape[1],
        condition_estimate=condition,
        roundoff_estimate=roundoff,
        relative_optimality_residual=residual,
        relative_prediction_residual=prediction_residual,
        fallback_reasons=tuple(reasons),
        precision_warning=precision_warning,
    )
    return coefs_out.to(states.device), (
        intercept.to(states.device) if intercept is not None else None
    )

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:

\[ ||XW - Y||^2 + \alpha ||W||^2 \]

where \(\alpha\) is the regularization strength.

PARAMETER DESCRIPTION
in_features

Size of input features (reservoir state dimension).

TYPE: int

out_features

Size of output features (prediction dimension).

TYPE: int

bias

Whether to include a bias term.

TYPE: bool DEFAULT: True

name

Name for this readout layer. Used for identification in multi-readout architectures and by ESNTrainer.

TYPE: str DEFAULT: None

trainable

If True, weights are trainable via backpropagation.

TYPE: bool DEFAULT: False

alpha

L2 regularization strength. Must be non-negative. Larger values provide more regularization (smoother outputs, less overfitting).

TYPE: float DEFAULT: 1e-6

max_iter

Maximum number of CG iterations. Must be a positive integer.

TYPE: int DEFAULT: 100

tol

Convergence tolerance for the CG solver. Must be positive. Each output column is considered converged when its residual-norm-squared falls below tol**2. This is an absolute criterion and depends on target units. Use explicit tighter tolerances or normalize targets when needed.

TYPE: float DEFAULT: 1e-5

use_float64

If True (default), the CG iterations on the small (in_features, in_features) system run in float64 and the result is cast back to the layer's parameter dtype. Gram formation uses the separate gram_dtype policy. Float64 support and throughput depend on the device; MPS requires use_float64=False.

TYPE: bool DEFAULT: True

gram_dtype

Dtype for forming the Gram matrix and right-hand side (the heavy (N, F) matmuls). Default None is automatic: float64 on CPU (cheap there), the input dtype on CUDA — float64 matmuls run at 1/32–1/64 speed on consumer GPUs and are the classic reason ESN training measures slower on GPU than CPU. Pass torch.float64 to force full-precision Gram formation on any device (needed only for badly scaled states, e.g. unnormalized inputs concatenated into the readout; prefer normalizing the data).

TYPE: dtype DEFAULT: None

ATTRIBUTE DESCRIPTION
weight

Weight matrix of shape (out_features, in_features).

TYPE: Parameter

bias

Bias vector of shape (out_features,), or None if bias=False.

TYPE: Parameter or None

alpha

L2 regularization strength.

TYPE: float

max_iter

Maximum CG iterations.

TYPE: int

tol

Convergence tolerance.

TYPE: float

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
def __init__(
    self,
    in_features: int,
    out_features: int,
    bias: bool = True,
    name: str | None = None,
    trainable: bool = False,
    max_iter: int = 100,
    tol: float = 1e-5,
    alpha: float = 1e-6,
    use_float64: bool = True,
    gram_dtype: torch.dtype | None = None,
) -> None:
    super().__init__(in_features, out_features, bias, name, trainable)
    if alpha < 0:
        raise ValueError(f"alpha must be non-negative, got {alpha}.")
    if tol <= 0:
        raise ValueError(f"tol must be positive, got {tol}.")
    if max_iter < 1:
        raise ValueError(f"max_iter must be a positive integer, got {max_iter}.")
    self.max_iter = max_iter
    self.tol = tol
    self.alpha = alpha
    self.use_float64 = use_float64
    self.gram_dtype = gram_dtype

solve

solve(states: Tensor, targets: Tensor) -> tuple[Tensor, Tensor | None]

Solve ridge regression via Conjugate Gradient on flattened inputs.

PARAMETER DESCRIPTION
states

Flattened state matrix of shape (N, in_features).

TYPE: Tensor

targets

Flattened target matrix of shape (N, out_features).

TYPE: Tensor

RETURNS DESCRIPTION
coefs

Coefficient matrix of shape (in_features, out_features).

TYPE: Tensor

intercept

Intercept vector of shape (out_features,), or None when the layer was built with bias=False (the ridge problem is then solved without centering, i.e. with no intercept).

TYPE: Tensor or None

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
def solve(
    self,
    states: torch.Tensor,
    targets: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor | None]:
    """Solve ridge regression via Conjugate Gradient on flattened inputs.

    Parameters
    ----------
    states : torch.Tensor
        Flattened state matrix of shape `(N, in_features)`.
    targets : torch.Tensor
        Flattened target matrix of shape `(N, out_features)`.

    Returns
    -------
    coefs : torch.Tensor
        Coefficient matrix of shape `(in_features, out_features)`.
    intercept : torch.Tensor or None
        Intercept vector of shape `(out_features,)`, or `None` when
        the layer was built with `bias=False` (the ridge problem is
        then solved without centering, i.e. with no intercept).
    """
    return self._solve_ridge_cg(states, targets, self.alpha)

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,

\[ \lVert X W - Y \rVert_2^2 + \alpha \lVert W \rVert_2^2 , \]

by forming the regularised normal equations (XᵀX + αI) W = Xᵀy and solving them with one of:

  • solver='cholesky' (default) — torch.linalg.cholesky followed by torch.linalg.cholesky_solve. Exploits the symmetric positive definiteness of XᵀX + αI in exact arithmetic for alpha > 0. Finite-precision Gram formation can still lose positive definiteness.
  • solver='solve' — torch.linalg.solve (LU). It does not require positive definiteness, so it supports alpha == 0 on a full-rank Gram.
Solver-selection guide
  • Default to RidgeReadoutLayer(solver='cholesky') for any well-conditioned readout with alpha > 0 when an explicit normal-equations solve is desired. Runtime and accuracy depend on the workload, precision and hardware. AutoReadoutLayer checks numerical safety and can use the original design matrix instead.
  • Use solver='solve' when you need alpha == 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) or PinvReadoutLayer (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: int

out_features

Size of output features (prediction dimension).

TYPE: int

bias

Whether to include a bias term. When True the data is centered and an unpenalised intercept is recovered; when False the raw normal equations are solved with no intercept.

TYPE: bool DEFAULT: True

name

Name for this readout layer. Used for identification in multi-readout architectures and as the key into targets by ESNTrainer.

TYPE: str DEFAULT: None

trainable

If True, weights are trainable via backpropagation.

TYPE: bool DEFAULT: False

alpha

L2 regularization strength. Must be non-negative. alpha == 0 is only safe with solver='solve' on a full-rank Gram.

TYPE: float DEFAULT: 1e-6

solver

Direct solver to use for the normal equations.

TYPE: (cholesky, solve) DEFAULT: 'cholesky'

state_noise

Standard deviation \(\sigma\) of the Gaussian state noise the readout is regularised against for closed-loop stability (see the class docstring). 0.0 (default) disables it — the fit is then byte-identical to a plain ridge solve. Must be non-negative.

TYPE: float DEFAULT: 0.0

noise_draws

When state_noise > 0: None (default) uses the closed-form LMNT term (one solve, exact expectation); an integer M >= 1 instead averages M noisy-state normal equations, then solves once (Monte-Carlo). Ignored when state_noise == 0.

TYPE: int DEFAULT: None

noise_seed

Seed for the explicit-noise (noise_draws) Gaussian draws, for reproducibility. None uses the process-global RNG. Ignored for the closed-form LMNT path (which is deterministic).

TYPE: int DEFAULT: None

use_float64

If True the small (F, F) factorisation runs in float64 and the result is cast back to the parameter dtype.

TYPE: bool DEFAULT: True

gram_dtype

Dtype for forming the Gram matrix and right-hand side (the heavy (N, F) matmuls). Default None uses the solve dtype (float64 with use_float64=True) on every device. An explicit gram_dtype=torch.float32 can speed up well-conditioned fits on CUDA, at the cost of precision when forming the normal equations.

TYPE: dtype DEFAULT: None

ATTRIBUTE DESCRIPTION
weight

Weight matrix of shape (out_features, in_features).

TYPE: Parameter

bias

Bias vector of shape (out_features,), or None if bias=False.

TYPE: Parameter or None

alpha

L2 regularization strength.

TYPE: float

solver

The selected direct solver.

TYPE: str

state_noise

Standard deviation of the closed-loop state-noise regulariser.

TYPE: float

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
def __init__(
    self,
    in_features: int,
    out_features: int,
    bias: bool = True,
    name: str | None = None,
    trainable: bool = False,
    alpha: float = 1e-6,
    solver: str = "cholesky",
    state_noise: float = 0.0,
    noise_draws: int | None = None,
    noise_seed: int | None = None,
    use_float64: bool = True,
    gram_dtype: torch.dtype | None = None,
) -> None:
    super().__init__(in_features, out_features, bias, name, trainable)
    if alpha < 0:
        raise ValueError(f"alpha must be non-negative, got {alpha}.")
    if solver not in self._VALID_SOLVERS:
        raise ValueError(f"solver must be one of {self._VALID_SOLVERS}, got {solver!r}.")
    if state_noise < 0:
        raise ValueError(f"state_noise must be non-negative, got {state_noise}.")
    if noise_draws is not None and noise_draws < 1:
        raise ValueError(f"noise_draws must be >= 1 when given, got {noise_draws}.")
    self.alpha = alpha
    self.solver = solver
    self.state_noise = state_noise
    self.noise_draws = noise_draws
    self.noise_seed = noise_seed
    self.use_float64 = use_float64
    self.gram_dtype = gram_dtype

solve

solve(states: Tensor, targets: Tensor) -> tuple[Tensor, Tensor | None]

Solve ridge regression directly on flattened inputs.

PARAMETER DESCRIPTION
states

Flattened state matrix of shape (N, in_features).

TYPE: Tensor

targets

Flattened target matrix of shape (N, out_features).

TYPE: Tensor

RETURNS DESCRIPTION
coefs

Coefficient matrix of shape (in_features, out_features).

TYPE: Tensor

intercept

Intercept vector of shape (out_features,), or None when the layer was built with bias=False.

TYPE: Tensor or None

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
def solve(
    self,
    states: torch.Tensor,
    targets: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor | None]:
    """Solve ridge regression directly on flattened inputs.

    Parameters
    ----------
    states : torch.Tensor
        Flattened state matrix of shape `(N, in_features)`.
    targets : torch.Tensor
        Flattened target matrix of shape `(N, out_features)`.

    Returns
    -------
    coefs : torch.Tensor
        Coefficient matrix of shape `(in_features, out_features)`.
    intercept : torch.Tensor or None
        Intercept vector of shape `(out_features,)`, or `None` when the
        layer was built with `bias=False`.
    """
    if self.state_noise > 0 and self.noise_draws is not None:
        # Explicit Monte-Carlo noise training: average M noisy normal equations.
        generator: torch.Generator | None = None
        if self.noise_seed is not None:
            generator = torch.Generator(device=states.device)
            generator.manual_seed(int(self.noise_seed))
        problem = build_noisy_ridge_problem(
            states,
            targets,
            fit_intercept=self.bias is not None,
            use_float64=self.use_float64,
            gram_dtype=self.gram_dtype,
            state_noise=self.state_noise,
            n_draws=self.noise_draws,
            generator=generator,
        )
    else:
        problem = build_ridge_problem(
            states,
            targets,
            fit_intercept=self.bias is not None,
            use_float64=self.use_float64,
            gram_dtype=self.gram_dtype,
        )
        # Closed-form LMNT: fold the analytic noise-covariance term into the
        # Gram diagonal (no-op when state_noise == 0, keeping the fit exact).
        apply_lmnt_regularizer(problem, self.state_noise)

    layer_name = (
        f"{type(self).__name__}('{self._name}')"
        if self._name is not None
        else type(self).__name__
    )

    if self.solver == "cholesky":
        coefs = solve_ridge(
            problem.gram,
            problem.rhs,
            self.alpha,
            layer_name=layer_name,
            gram_dtype=problem.X.dtype,
        )
    else:  # "solve" — general LU. Does not need positive-definiteness, so
        # it tolerates alpha == 0 on a full-rank Gram; it still benefits
        # from the shared post-solve accuracy residual guard.
        eye = torch.eye(
            problem.n_features,
            dtype=problem.solve_dtype,
            device=problem.gram.device,
        )
        coefs = torch.linalg.solve(problem.gram + self.alpha * eye, problem.rhs)
        _warn_on_precision_loss(
            gram=problem.gram,
            coefs=coefs,
            rhs=problem.rhs,
            alpha_eff=self.alpha,
            cond_estimate=None,
            gram_dtype=problem.X.dtype,
            layer_name=layer_name,
        )

    return finalize_fit(problem, coefs)

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,

\[ \lVert X W - Y \rVert_2^2 + \alpha \lVert W \rVert_2^2 . \]
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: int

out_features

Size of output features (prediction dimension).

TYPE: int

bias

Whether to include a bias term. When True the data is centered and an unpenalised intercept is recovered; when False the raw normal equations are solved with no intercept.

TYPE: bool DEFAULT: True

name

Name for this readout layer. Used for identification in multi-readout architectures and as the key into targets by ESNTrainer.

TYPE: str DEFAULT: None

trainable

If True, weights are trainable via backpropagation.

TYPE: bool DEFAULT: False

alpha

L2 regularization strength. Must be non-negative. alpha > 0 guarantees the Gram is positive definite; with alpha == 0 the factorisation succeeds only on a full-rank Gram (reach for SVDReadoutLayer if the Gram may be rank deficient).

TYPE: float DEFAULT: 1e-6

state_noise

Standard deviation \(\sigma\) of the closed-loop state-noise regulariser (see the class docstring). 0.0 (default) is byte-identical to a plain fit. Must be non-negative. Adds alpha > 0 positive definiteness insurance too — the LMNT term is a positive diagonal add.

TYPE: float DEFAULT: 0.0

noise_draws

None (default) uses the closed-form LMNT term; an integer M >= 1 averages M noisy-state normal equations before one solve. Ignored when state_noise == 0.

TYPE: int DEFAULT: None

noise_seed

Seed for the explicit-noise (noise_draws) draws. Ignored for the deterministic LMNT path.

TYPE: int DEFAULT: None

use_float64

If True the small (F, F) factorisation runs in float64 and the result is cast back to the parameter dtype.

TYPE: bool DEFAULT: True

gram_dtype

Dtype for forming the Gram matrix and right-hand side (the heavy (N, F) matmuls). Default None uses the solve dtype (float64 with use_float64=True) on every device. An explicit gram_dtype=torch.float32 can speed up well-conditioned fits on CUDA, at the cost of precision when forming the normal equations.

TYPE: dtype DEFAULT: None

ATTRIBUTE DESCRIPTION
weight

Weight matrix of shape (out_features, in_features).

TYPE: Parameter

bias

Bias vector of shape (out_features,), or None if bias=False.

TYPE: Parameter or None

alpha

L2 regularization strength.

TYPE: float

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
def __init__(
    self,
    in_features: int,
    out_features: int,
    bias: bool = True,
    name: str | None = None,
    trainable: bool = False,
    alpha: float = 1e-6,
    state_noise: float = 0.0,
    noise_draws: int | None = None,
    noise_seed: int | None = None,
    use_float64: bool = True,
    gram_dtype: torch.dtype | None = None,
) -> None:
    super().__init__(in_features, out_features, bias, name, trainable)
    if alpha < 0:
        raise ValueError(f"alpha must be non-negative, got {alpha}.")
    if state_noise < 0:
        raise ValueError(f"state_noise must be non-negative, got {state_noise}.")
    if noise_draws is not None and noise_draws < 1:
        raise ValueError(f"noise_draws must be >= 1 when given, got {noise_draws}.")
    self.alpha = alpha
    self.state_noise = state_noise
    self.noise_draws = noise_draws
    self.noise_seed = noise_seed
    self.use_float64 = use_float64
    self.gram_dtype = gram_dtype

solve

solve(states: Tensor, targets: Tensor) -> tuple[Tensor, Tensor | None]

Solve ridge regression via a Cholesky factorisation on flattened inputs.

PARAMETER DESCRIPTION
states

Flattened state matrix of shape (N, in_features).

TYPE: Tensor

targets

Flattened target matrix of shape (N, out_features).

TYPE: Tensor

RETURNS DESCRIPTION
coefs

Coefficient matrix of shape (in_features, out_features).

TYPE: Tensor

intercept

Intercept vector of shape (out_features,), or None when the layer was built with bias=False.

TYPE: Tensor or None

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
def solve(
    self,
    states: torch.Tensor,
    targets: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor | None]:
    """Solve ridge regression via a Cholesky factorisation on flattened inputs.

    Parameters
    ----------
    states : torch.Tensor
        Flattened state matrix of shape `(N, in_features)`.
    targets : torch.Tensor
        Flattened target matrix of shape `(N, out_features)`.

    Returns
    -------
    coefs : torch.Tensor
        Coefficient matrix of shape `(in_features, out_features)`.
    intercept : torch.Tensor or None
        Intercept vector of shape `(out_features,)`, or `None` when the
        layer was built with `bias=False`.
    """
    if self.state_noise > 0 and self.noise_draws is not None:
        generator: torch.Generator | None = None
        if self.noise_seed is not None:
            generator = torch.Generator(device=states.device)
            generator.manual_seed(int(self.noise_seed))
        problem = build_noisy_ridge_problem(
            states,
            targets,
            fit_intercept=self.bias is not None,
            use_float64=self.use_float64,
            gram_dtype=self.gram_dtype,
            state_noise=self.state_noise,
            n_draws=self.noise_draws,
            generator=generator,
        )
    else:
        problem = build_ridge_problem(
            states,
            targets,
            fit_intercept=self.bias is not None,
            use_float64=self.use_float64,
            gram_dtype=self.gram_dtype,
        )
        apply_lmnt_regularizer(problem, self.state_noise)

    layer_name = (
        f"{type(self).__name__}('{self._name}')"
        if self._name is not None
        else type(self).__name__
    )
    coefs = solve_ridge(
        problem.gram,
        problem.rhs,
        self.alpha,
        layer_name=layer_name,
        gram_dtype=problem.X.dtype,
    )

    return finalize_fit(problem, coefs)

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

\[ W = V \, \operatorname{diag}\!\left(\frac{s}{s^2 + \alpha}\right) U^\top Y . \]

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 SVDReadoutLayer when the Gram is rank deficient or severely ill-conditioned: alpha == 0 least squares, high-degree NG-RC feature maps, or wide concatenated-input readouts where CG under-converges.
  • Cholesky-based RidgeReadoutLayer can 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.
  • PinvReadoutLayer is the closely-related lstsq / pinv route; SVD here gives explicit control over the Tikhonov filter and rcond.
PARAMETER DESCRIPTION
in_features

Size of input features (reservoir state dimension).

TYPE: int

out_features

Size of output features (prediction dimension).

TYPE: int

bias

Whether to include a bias term. When True the data is centered and an unpenalised intercept is recovered; when False the raw design matrix is decomposed with no intercept.

TYPE: bool DEFAULT: True

name

Name for this readout layer. Used for identification in multi-readout architectures and as the key into targets by ESNTrainer.

TYPE: str DEFAULT: None

trainable

If True, weights are trainable via backpropagation.

TYPE: bool DEFAULT: False

alpha

Tikhonov (L2) regularization strength. Must be finite and non-negative. 0 is fully supported and yields the minimum-norm least-squares solution.

TYPE: float DEFAULT: 0.0

rcond

Finite, non-negative relative cutoff for small singular values. Values at or below rcond * s_max are treated as zero (their filter factor is set to zero), which is what makes rank-deficient problems well posed. Only active for alpha == 0; for alpha > 0 the Tikhonov filter already damps small singular values.

TYPE: float DEFAULT: 1e-15

use_float64

If True the SVD runs in float64 and the result is cast back to the parameter dtype.

TYPE: bool DEFAULT: True

gram_dtype

Dtype for forming / casting the design matrix. Default None is the solve dtype (float64 with use_float64=True) on every device. No Gram matrix is formed; the decomposition operates directly on the design matrix.

TYPE: dtype DEFAULT: None

ATTRIBUTE DESCRIPTION
weight

Weight matrix of shape (out_features, in_features).

TYPE: Parameter

bias

Bias vector of shape (out_features,), or None if bias=False.

TYPE: Parameter or None

alpha

Tikhonov regularization strength.

TYPE: float

rcond

Relative singular-value cutoff.

TYPE: float

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
def __init__(
    self,
    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: torch.dtype | None = None,
) -> None:
    super().__init__(in_features, out_features, bias, name, trainable)
    _validate_regularization(alpha, rcond)
    self.alpha = alpha
    self.rcond = rcond
    self.use_float64 = use_float64
    self.gram_dtype = gram_dtype

solve

solve(states: Tensor, targets: Tensor) -> tuple[Tensor, Tensor | None]

Solve the readout via SVD filter factors on flattened inputs.

PARAMETER DESCRIPTION
states

Flattened state matrix of shape (N, in_features).

TYPE: Tensor

targets

Flattened target matrix of shape (N, out_features).

TYPE: Tensor

RETURNS DESCRIPTION
coefs

Coefficient matrix of shape (in_features, out_features).

TYPE: Tensor

intercept

Intercept vector of shape (out_features,), or None when the layer was built with bias=False.

TYPE: Tensor or None

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
def solve(
    self,
    states: torch.Tensor,
    targets: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor | None]:
    """Solve the readout via SVD filter factors on flattened inputs.

    Parameters
    ----------
    states : torch.Tensor
        Flattened state matrix of shape `(N, in_features)`.
    targets : torch.Tensor
        Flattened target matrix of shape `(N, out_features)`.

    Returns
    -------
    coefs : torch.Tensor
        Coefficient matrix of shape `(in_features, out_features)`.
    intercept : torch.Tensor or None
        Intercept vector of shape `(out_features,)`, or `None` when the
        layer was built with `bias=False`.
    """
    _validate_regularization(self.alpha, self.rcond)
    problem = build_least_squares_problem(
        states,
        targets,
        fit_intercept=self.bias is not None,
        use_float64=self.use_float64,
        gram_dtype=self.gram_dtype,
    )

    # Operate on the centered design matrix when an intercept is fitted so
    # the SVD sees the same problem the Gram-based solvers do. The means
    # carried by ``problem`` reproduce the analytic centering exactly.
    x = problem.X.to(problem.solve_dtype)
    y = problem.y.to(problem.solve_dtype)
    if problem.fit_intercept:
        assert problem.x_mean is not None and problem.y_mean is not None
        x = x - problem.x_mean.to(problem.solve_dtype)
        y = y - problem.y_mean.to(problem.solve_dtype)

    # Economy SVD of the (N, F) design matrix.
    u, s, vh = torch.linalg.svd(x, full_matrices=False)

    # Tikhonov filter factors s / (s^2 + alpha). For alpha == 0 this is
    # 1 / s on the retained singular values and 0 on those at/below the
    # rcond cutoff (the minimum-norm least-squares pseudo-inverse).
    if self.alpha > 0:
        filt = _ridge_filter(s, self.alpha)
    else:
        cutoff = self.rcond * s.max() if s.numel() > 0 else s.new_zeros(())
        retained = s > cutoff
        safe_s = torch.where(retained, s, torch.ones_like(s))
        inv_s = torch.where(retained, 1.0 / safe_s, torch.zeros_like(s))
        filt = inv_s

    # W = V diag(filt) Uᵀ y  with vh = Vᵀ, so V = vh.T.
    coefs = vh.T @ (filt.unsqueeze(1) * (u.T @ y))

    return finalize_fit(problem, coefs)

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.lstsq with the gelsd driver, a divide-and-conquer SVD-based least-squares solver that returns the minimum-norm solution for rank-deficient X and honours the rcond cutoff.
  • solver='pinv' — form the Moore–Penrose pseudo-inverse torch.linalg.pinv(X, rcond=...) and apply it to Y. 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 PinvReadoutLayer for unregularised least squares on a possibly rank-deficient design matrix when you want the minimum-norm solution and don't need a Tikhonov alpha.
  • solver='lstsq' (default) is the right choice almost always — it never materialises the pseudo-inverse. Use solver='pinv' only if you specifically want the pseudo-inverse matrix itself.
  • For an explicit ridge penalty, prefer SVDReadoutLayer (filter factors, alpha + rcond) or RidgeReadoutLayer (Cholesky, fast, full rank).
PARAMETER DESCRIPTION
in_features

Size of input features (reservoir state dimension).

TYPE: int

out_features

Size of output features (prediction dimension).

TYPE: int

bias

Whether to include a bias term. When True the data is centered and an unpenalised intercept is recovered; when False the raw design matrix is used with no intercept.

TYPE: bool DEFAULT: True

name

Name for this readout layer. Used for identification in multi-readout architectures and as the key into targets by ESNTrainer.

TYPE: str DEFAULT: None

trainable

If True, weights are trainable via backpropagation.

TYPE: bool DEFAULT: False

rcond

Relative cutoff for small singular values. Singular values at or below rcond * s_max are dropped, making rank-deficient problems well posed.

TYPE: float DEFAULT: 1e-15

solver

Whether to solve with torch.linalg.lstsq or an explicit torch.linalg.pinv.

TYPE: (lstsq, pinv) DEFAULT: 'lstsq'

use_float64

If True the least-squares solve runs in float64 and the result is cast back to the parameter dtype.

TYPE: bool DEFAULT: True

gram_dtype

Dtype for forming / casting the design matrix. Default None is the solve dtype (float64 with use_float64=True) on every device. No Gram matrix is formed; the decomposition operates directly on the design matrix.

TYPE: dtype DEFAULT: None

ATTRIBUTE DESCRIPTION
weight

Weight matrix of shape (out_features, in_features).

TYPE: Parameter

bias

Bias vector of shape (out_features,), or None if bias=False.

TYPE: Parameter or None

rcond

Relative singular-value cutoff.

TYPE: float

solver

The selected least-squares solver.

TYPE: str

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
def __init__(
    self,
    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: torch.dtype | None = None,
) -> None:
    super().__init__(in_features, out_features, bias, name, trainable)
    if rcond < 0:
        raise ValueError(f"rcond must be non-negative, got {rcond}.")
    if solver not in self._VALID_SOLVERS:
        raise ValueError(f"solver must be one of {self._VALID_SOLVERS}, got {solver!r}.")
    self.rcond = rcond
    self.solver = solver
    self.use_float64 = use_float64
    self.gram_dtype = gram_dtype

solve

solve(states: Tensor, targets: Tensor) -> tuple[Tensor, Tensor | None]

Solve the readout via least squares / pinv on flattened inputs.

PARAMETER DESCRIPTION
states

Flattened state matrix of shape (N, in_features).

TYPE: Tensor

targets

Flattened target matrix of shape (N, out_features).

TYPE: Tensor

RETURNS DESCRIPTION
coefs

Coefficient matrix of shape (in_features, out_features).

TYPE: Tensor

intercept

Intercept vector of shape (out_features,), or None when the layer was built with bias=False.

TYPE: Tensor or None

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
def solve(
    self,
    states: torch.Tensor,
    targets: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor | None]:
    """Solve the readout via least squares / pinv on flattened inputs.

    Parameters
    ----------
    states : torch.Tensor
        Flattened state matrix of shape `(N, in_features)`.
    targets : torch.Tensor
        Flattened target matrix of shape `(N, out_features)`.

    Returns
    -------
    coefs : torch.Tensor
        Coefficient matrix of shape `(in_features, out_features)`.
    intercept : torch.Tensor or None
        Intercept vector of shape `(out_features,)`, or `None` when the
        layer was built with `bias=False`.
    """
    # No Tikhonov penalty here: the normal-equations Gram is unused, so
    # build the problem only to share the centering / precision machinery.
    problem = build_least_squares_problem(
        states,
        targets,
        fit_intercept=self.bias is not None,
        use_float64=self.use_float64,
        gram_dtype=self.gram_dtype,
    )

    x = problem.X.to(problem.solve_dtype)
    y = problem.y.to(problem.solve_dtype)
    if problem.fit_intercept:
        assert problem.x_mean is not None and problem.y_mean is not None
        x = x - problem.x_mean.to(problem.solve_dtype)
        y = y - problem.y_mean.to(problem.solve_dtype)

    if self.solver == "lstsq" and x.device.type == "cpu":
        # gelsd is SVD-based and handles rank-deficient X with rcond, but
        # it is CPU-only — torch.linalg.lstsq on CUDA supports only the
        # full-rank ``gels`` driver, which silently mishandles rank
        # deficiency. On CUDA we therefore route ``lstsq`` through the
        # SVD-based pseudo-inverse, which is equally robust there.
        result = torch.linalg.lstsq(x, y, rcond=self.rcond, driver="gelsd")
        coefs = result.solution
    else:  # "pinv", or "lstsq" on a non-CPU device
        coefs = torch.linalg.pinv(x, rcond=self.rcond) @ y

    return finalize_fit(problem, coefs)

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 when bias=True and raw products when bias=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,

\[ \lVert X W - Y \rVert_2^2 + \alpha \lVert W \rVert_2^2 , \]

with the intercept (when bias=True) recovered from the running means and left un-penalised, exactly as in the shared _solve_utils centering.

Lifecycle
  1. (Optionally) reset_accumulators to clear any prior statistics.
  2. Call partial_fit once per chunk to accumulate statistics.
  3. Call finalize once 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: int

out_features

Size of output features (prediction dimension).

TYPE: int

bias

Whether to include a bias term. When True the running means center the data and an un-penalised intercept is recovered; when False the raw normal equations are solved with no intercept.

TYPE: bool DEFAULT: True

name

Name for this readout layer. Used for identification in multi-readout architectures and as the key into targets by ESNTrainer.

TYPE: str DEFAULT: None

trainable

If True, weights are trainable via backpropagation.

TYPE: bool DEFAULT: False

alpha

L2 regularization strength. Must be non-negative.

TYPE: float DEFAULT: 1e-6

use_float64

If True the accumulator buffers and the small (F, F) solve run in float64 and the fitted weights are cast back to the parameter dtype. Parameter casts such as .float() preserve float64 working statistics. MPS cannot hold these statistics; use CPU or explicitly opt out with use_float64=False for supported MPS operations.

TYPE: bool DEFAULT: True

gram_dtype

Dtype the per-chunk Gram matmuls run in. Default None is automatic: the solve dtype (float64 with use_float64=True) on every device. Pass torch.float32 explicitly for faster, lower-precision Gram formation on CUDA when the feature matrix is well-conditioned.

TYPE: dtype DEFAULT: None

ATTRIBUTE DESCRIPTION
weight

Weight matrix of shape (out_features, in_features).

TYPE: Parameter

bias

Bias vector of shape (out_features,), or None if bias=False.

TYPE: Parameter or None

alpha

L2 regularization strength.

TYPE: float

n_seen

Number of samples accumulated so far (across all chunks).

TYPE: int

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
def __init__(
    self,
    in_features: int,
    out_features: int,
    bias: bool = True,
    name: str | None = None,
    trainable: bool = False,
    alpha: float = 1e-6,
    use_float64: bool = True,
    gram_dtype: torch.dtype | None = None,
) -> None:
    super().__init__(in_features, out_features, bias, name, trainable)
    if alpha < 0:
        raise ValueError(f"alpha must be non-negative, got {alpha}.")
    self.alpha = alpha
    self.use_float64 = use_float64
    self.gram_dtype = gram_dtype

    # When True the forward guard is bypassed: the layer may run unfitted.
    # Used internally during graph construction (where ``pytorch_symbolic``
    # traces shapes by calling ``forward`` once) and during the trainer's
    # streaming accumulation pass (where ``forward`` only needs to flow a
    # value downstream while the pre-hook accumulates statistics). Never a
    # public attribute — genuine inference always goes through the guard.
    self._allow_unfitted_forward = False

    # Accumulator dtype: float64 when use_float64 (cheap on the small
    # (F, F) / (F, T) buffers and avoids drift across many chunks).
    acc_dtype = resolve_solve_dtype(self.weight.dtype, use_float64)
    # Persistent buffers so accumulation state survives state_dict
    # round-trips and rides along with .to(device) / .to(dtype).
    self.register_buffer("XtX", torch.zeros(in_features, in_features, dtype=acc_dtype))
    self.register_buffer("Xty", torch.zeros(in_features, out_features, dtype=acc_dtype))
    self.register_buffer("sum_x", torch.zeros(in_features, dtype=acc_dtype))
    self.register_buffer("sum_y", torch.zeros(out_features, dtype=acc_dtype))
    self.register_buffer("_mean_x", torch.zeros(in_features, dtype=acc_dtype))
    self.register_buffer("_mean_y", torch.zeros(out_features, dtype=acc_dtype))
    # Version 1 stores centered cross-products when bias=True. Legacy
    # checkpoints had no version and stored cancellation-prone raw moments.
    self.register_buffer("_statistics_version", torch.ones((), dtype=torch.long))
    self.register_buffer("_n", torch.zeros((), dtype=torch.long))

    # Dtype the per-chunk Gram matmuls actually ran in (resolved from the
    # first chunk in ``partial_fit``). Recorded so ``finalize``'s accuracy
    # guard weights its condition estimate by the right machine epsilon —
    # the precision loss happens at the float32 matmul, before the float64
    # accumulation, so the accumulator dtype would understate it.
    self._chunk_gram_dtype: torch.dtype | None = None

n_seen property

n_seen: int

int : Number of samples accumulated across all partial_fit calls.

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
@torch.no_grad()
def reset_accumulators(self) -> 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.
    """
    self.XtX.zero_()
    self.Xty.zero_()
    self.sum_x.zero_()
    self.sum_y.zero_()
    self._mean_x.zero_()
    self._mean_y.zero_()
    self._n.zero_()
    self._chunk_gram_dtype = None
    self._set_fitted(False)

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 (B, T, F_in) or (N, F_in).

TYPE: Tensor

targets

Target chunk of shape (B, T, F_out) or (N, F_out).

TYPE: Tensor

RETURNS DESCRIPTION
IncrementalRidgeReadoutLayer

self, so calls can be chained.

RAISES DESCRIPTION
ValueError

If states and targets disagree on the sample dimension after flattening, if the state feature dimension does not match in_features, if the target feature dimension does not match out_features, or if states or targets contain non-finite (NaN or Inf) values.

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
@torch.no_grad()
def partial_fit(
    self, states: torch.Tensor, targets: torch.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.

    Parameters
    ----------
    states : torch.Tensor
        State chunk of shape `(B, T, F_in)` or `(N, F_in)`.
    targets : torch.Tensor
        Target chunk of shape `(B, T, F_out)` or `(N, F_out)`.

    Returns
    -------
    IncrementalRidgeReadoutLayer
        `self`, so calls can be chained.

    Raises
    ------
    ValueError
        If `states` and `targets` disagree on the sample dimension after
        flattening, if the state feature dimension does not match
        `in_features`, if the target feature dimension does not match
        `out_features`, or if `states` or `targets` contain non-finite
        (NaN or Inf) values.
    """
    states, targets = self._prepare_fit_inputs(states, targets, "partial_fit")

    # Form each chunk in the requested Gram dtype (float64 by default),
    # then merge into buffers in their independently configured working dtype.
    solve_dtype = resolve_solve_dtype(states.dtype, self.use_float64)
    gram_dtype = resolve_gram_dtype(states.dtype, states.device, solve_dtype, self.gram_dtype)
    self._chunk_gram_dtype = gram_dtype
    x = states.to(gram_dtype)
    y = targets.to(gram_dtype)

    acc_dtype = self.XtX.dtype
    if self.bias is not None:
        chunk_mean_x = x.mean(dim=0)
        chunk_mean_y = y.mean(dim=0)
        centered_x = x - chunk_mean_x
        centered_y = y - chunk_mean_y
        delta_x = chunk_mean_x.to(acc_dtype) - self._mean_x
        delta_y = chunk_mean_y.to(acc_dtype) - self._mean_y
        old_count = self._n.to(acc_dtype)
        total = old_count + states.shape[0]
        correction = old_count * states.shape[0] / total
        self.XtX.add_((centered_x.T @ centered_x).to(acc_dtype))
        self.Xty.add_((centered_x.T @ centered_y).to(acc_dtype))
        self.XtX.addmm_(delta_x[:, None], (correction * delta_x)[None, :])
        self.Xty.addmm_(delta_x[:, None], (correction * delta_y)[None, :])
        self._mean_x.add_(delta_x * (states.shape[0] / total))
        self._mean_y.add_(delta_y * (states.shape[0] / total))
    else:
        self.XtX += (x.T @ x).to(acc_dtype)
        self.Xty += (x.T @ y).to(acc_dtype)
    self.sum_x += x.sum(dim=0).to(acc_dtype)
    self.sum_y += y.sum(dim=0).to(acc_dtype)
    self._n += states.shape[0]

    # Any prior fit is stale once new data arrives.
    self._set_fitted(False)
    return self

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 (partial_fit was never called, or reset_accumulators was called since).

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
@torch.no_grad()
def finalize(self) -> 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
    ------
    RuntimeError
        If no samples have been accumulated (`partial_fit` was never
        called, or `reset_accumulators` was called since).

    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.
    """
    n = self.n_seen
    if n == 0:
        readout_id = f"'{self._name}'" if self._name is not None else type(self).__name__
        raise RuntimeError(
            f"{type(self).__name__}.finalize({readout_id}): no data accumulated. "
            f"Call partial_fit(states, targets) at least once before finalize()."
        )

    fit_intercept = self.bias is not None
    gram = self.XtX
    rhs = self.Xty

    layer_name = (
        f"{type(self).__name__}('{self._name}')"
        if self._name is not None
        else type(self).__name__
    )
    coefs = solve_ridge(  # (F, T)
        gram,
        rhs,
        self.alpha,
        layer_name=layer_name,
        gram_dtype=self._chunk_gram_dtype,
    )

    intercept = None
    if fit_intercept and self.bias is not None:
        intercept = self._mean_y - self._mean_x @ coefs
    self._copy_coefficients(coefs, intercept)

    self._set_fitted(True)

solve

solve(states: Tensor, targets: Tensor) -> tuple[Tensor, Tensor | None]

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 (N, in_features).

TYPE: Tensor

targets

Flattened target matrix of shape (N, out_features).

TYPE: Tensor

RETURNS DESCRIPTION
coefs

Coefficient matrix of shape (in_features, out_features).

TYPE: Tensor

intercept

Intercept vector of shape (out_features,), or None when the layer was built with bias=False.

TYPE: Tensor or None

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
def solve(
    self,
    states: torch.Tensor,
    targets: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor | None]:
    """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.

    Parameters
    ----------
    states : torch.Tensor
        Flattened state matrix of shape `(N, in_features)`.
    targets : torch.Tensor
        Flattened target matrix of shape `(N, out_features)`.

    Returns
    -------
    coefs : torch.Tensor
        Coefficient matrix of shape `(in_features, out_features)`.
    intercept : torch.Tensor or None
        Intercept vector of shape `(out_features,)`, or `None` when the
        layer was built with `bias=False`.
    """
    self.reset_accumulators()
    self.partial_fit(states, targets)
    self.finalize()
    # ``finalize`` already wrote the parameters and flipped is_fitted; hand
    # the base ``fit`` the same values so its copy-back is a harmless no-op.
    coefs = self.weight.T.to(states.dtype)
    intercept = None if self.bias is None else self.bias.to(states.dtype)
    return coefs, intercept

forward

forward(input: Tensor) -> Tensor

Apply the fitted linear transformation to input.

PARAMETER DESCRIPTION
input

Input tensor of shape (B, F) or (B, T, F).

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Output tensor of shape (B, F_out) or (B, T, F_out).

RAISES DESCRIPTION
RuntimeError

If finalize has not been called since the last partial_fit / construction. The error names the layer and points at finalize() so the streaming lifecycle is unambiguous.

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
def forward(self, input: torch.Tensor) -> torch.Tensor:
    """Apply the fitted linear transformation to `input`.

    Parameters
    ----------
    input : torch.Tensor
        Input tensor of shape `(B, F)` or `(B, T, F)`.

    Returns
    -------
    torch.Tensor
        Output tensor of shape `(B, F_out)` or `(B, T, F_out)`.

    Raises
    ------
    RuntimeError
        If `finalize` has not been called since the last
        `partial_fit` / construction. The error names the layer and points
        at `finalize()` so the streaming lifecycle is unambiguous.

    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.
    """
    # Compiled fast path: never let dynamo trace the guard (a graph break
    # per step forfeits the compiled forecast). The eager warmup pass that
    # forecast runs first already trips the guard for an unfitted readout,
    # so skipping the per-step guard under compile is safe here.
    if torch.compiler.is_compiling():
        return super().forward(input)

    # Eager path: the fitted bool read is sync-free; the frame walk (the
    # expensive part) only runs when genuinely unfitted, i.e. rarely.
    if not self._fitted_flag and not self._allow_unfitted_forward and not _in_symbolic_build():
        readout_id = f"'{self._name}'" if self._name is not None else type(self).__name__
        raise RuntimeError(
            f"{type(self).__name__}({readout_id}) is not fitted: call finalize() after "
            f"partial_fit(...) before forward/inference. "
            f"({self.n_seen} sample(s) accumulated so far.)"
        )
    return super().forward(input)

IncrementalRidgeReadout

IncrementalRidgeReadout(*args: Any, **kwargs: Any)

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
def __init__(self, *args: Any, **kwargs: Any) -> None:
    warnings.warn(
        "IncrementalRidgeReadout is deprecated and will be removed in a future "
        "release; use IncrementalRidgeReadoutLayer instead.",
        DeprecationWarning,
        stacklevel=2,
    )
    super().__init__(*args, **kwargs)

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:

\[ \begin{aligned} g_t &= P_{t-1}\, x_t \\ k_t &= g_t / (\lambda + x_t^\top g_t) \\ e_t &= d_t - W_{t-1}^\top x_t \\ W_t &= W_{t-1} + k_t\, e_t^\top \\ P_t &= (P_{t-1} - k_t\, g_t^\top) / \lambda \end{aligned} \]

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 (small alpha) 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 F (reservoir state dimension).

TYPE: int

out_features

Size of output features O (prediction dimension).

TYPE: int

bias

Whether to include a bias term. When True a constant 1 feature is appended to every input internally, so the intercept is estimated by the same RLS recursion as the slopes (and, like the slopes, is subject to the \(\delta\) prior — it is not separately un-penalised as in the centered batch solvers). When False no intercept is fitted.

TYPE: bool DEFAULT: True

name

Name for this readout layer. Used for identification in multi-readout architectures and as the key into targets by ESNTrainer.

TYPE: str DEFAULT: None

trainable

If True, weights are trainable via backpropagation after fitting.

TYPE: bool DEFAULT: False

forgetting

The forgetting factor \(\lambda \in (0, 1]\). 1.0 is growing-window RLS (converges to ordinary least squares); values < 1 exponentially forget old samples to track non-stationarity. Must be in (0, 1].

TYPE: float DEFAULT: 1.0

delta

Initialises \(P = I / \delta\) (default 1e-2 when neither delta nor alpha is given). Acts as a soft ridge prior on the early, data-starved updates: a larger delta shrinks the initial weights harder (a stronger prior), a smaller delta trusts the first samples more. Must be positive. Aliased by alpha — see below.

TYPE: float DEFAULT: None

alpha

Alias for delta (the two name the same ridge-prior knob: \(P_0 = I / \alpha\)). Ridge readouts spell this regularisation strength alpha, so it is accepted here too for API symmetry. Passing both alpha and a non-default delta raises. Must be positive.

TYPE: float DEFAULT: None

use_float64

If True the P recursion and the weight updates run in float64 (the fitted parameters are cast back to the layer dtype). The rank-1 \(P\) update accumulates round-off over many steps, so double precision materially improves stability; it is cheap because the per-step work is only O(F^2). Parameter casts such as .float() preserve this working precision. MPS does not support float64 statistics; use CPU or explicitly opt out with use_float64=False for supported lower-precision operations.

TYPE: bool DEFAULT: True

device

Device for the layer parameters and the P buffer.

TYPE: device DEFAULT: None

dtype

Dtype for the nn.Linear parameters.

TYPE: dtype DEFAULT: None

ATTRIBUTE DESCRIPTION
weight

Weight matrix of shape (out_features, in_features).

TYPE: Parameter

bias

Bias vector of shape (out_features,), or None if bias=False.

TYPE: Parameter or None

P

The (F', F') inverse-correlation buffer, where F' = F + 1 when a bias is fitted (the appended constant feature) and F otherwise. A persistent buffer, so it rides along with state_dict / .to(...).

TYPE: Tensor

forgetting

The forgetting factor \(\lambda\).

TYPE: float

delta

The \(P\) initialisation constant.

TYPE: float

n_seen

Number of samples applied across all partial_fit calls since the last reset.

TYPE: int

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
def __init__(
    self,
    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: torch.device | None = None,
    dtype: torch.dtype | None = None,
) -> None:
    super().__init__(in_features, out_features, bias, name, trainable)
    if device is not None or dtype is not None:
        # nn.Linear does not forward device/dtype in the resdag readout
        # signature, so move the freshly-created parameters explicitly. This
        # keeps the constructor signature aligned with the family's
        # device/dtype ergonomics without materialising a second Linear.
        self.to(device=device, dtype=dtype)

    if not 0.0 < forgetting <= 1.0:
        raise ValueError(f"forgetting (lambda) must be in (0, 1], got {forgetting}.")
    # ``alpha`` is an alias for ``delta`` (both parameterise P_0 = I / delta).
    # ``delta`` defaults to ``None`` (sentinel for "unset") so passing both
    # explicitly is detectable and rejected; the documented default is 1e-2.
    if alpha is not None and delta is not None:
        raise ValueError(
            "Pass either 'alpha' or 'delta' to RLSReadout, not both "
            f"(got alpha={alpha}, delta={delta}); they name the same "
            "P-initialisation knob P_0 = I / delta."
        )
    if alpha is not None:
        delta = alpha
    if delta is None:
        delta = 1e-2
    if delta <= 0.0:
        raise ValueError(f"delta (alpha) must be positive, got {delta}.")

    self.forgetting = forgetting
    self.delta = delta
    self.use_float64 = use_float64

    # The RLS recursion runs over an augmented feature space when a bias is
    # fitted: a constant 1 is appended to every input so the intercept is
    # learned by the same recursion. P therefore has size F' = F (+ 1).
    self._p_dim = in_features + 1 if self.bias is not None else in_features
    recur_dtype = resolve_solve_dtype(self.weight.dtype, use_float64)
    self.register_buffer(
        "P",
        torch.eye(self._p_dim, dtype=recur_dtype, device=self.weight.device) / self.delta,
    )
    self.register_buffer("_n", torch.zeros((), dtype=torch.long, device=self.weight.device))
    # A fresh partial_fit stream has the same zero coefficient prior as
    # fit_online/reset_state, including in unobserved feature directions.
    self.reset_state()

n_seen property

n_seen: int

int : Number of samples applied across all partial_fit calls.

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
@torch.no_grad()
def reset_state(self) -> 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.
    """
    eye = torch.eye(self._p_dim, dtype=self.P.dtype, device=self.P.device)
    self.P.copy_(eye / self.delta)
    self.weight.zero_()
    if self.bias is not None:
        self.bias.zero_()
    self._n.zero_()
    self._set_fitted(False)

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 (B, T, F_in) or (N, F_in).

TYPE: Tensor

targets

Target chunk of shape (B, T, F_out) or (N, F_out).

TYPE: Tensor

RETURNS DESCRIPTION
RLSReadout

self, so calls can be chained.

RAISES DESCRIPTION
ValueError

If states and targets disagree on the sample dimension after flattening, if the state feature dimension does not match in_features, if the target feature dimension does not match out_features, or if states or targets contain non-finite (NaN or Inf) values.

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
@torch.no_grad()
def partial_fit(self, states: torch.Tensor, targets: torch.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.

    Parameters
    ----------
    states : torch.Tensor
        State chunk of shape `(B, T, F_in)` or `(N, F_in)`.
    targets : torch.Tensor
        Target chunk of shape `(B, T, F_out)` or `(N, F_out)`.

    Returns
    -------
    RLSReadout
        `self`, so calls can be chained.

    Raises
    ------
    ValueError
        If `states` and `targets` disagree on the sample dimension after
        flattening, if the state feature dimension does not match
        `in_features`, if the target feature dimension does not match
        `out_features`, or if `states` or `targets` contain non-finite
        (NaN or Inf) values.
    """
    states, targets = self._validate_chunk(states, targets, "partial_fit")
    self._rls_update(states, targets)
    # RLS refines the actual weights every step, so the layer is usable for
    # inference the moment any data has been applied.
    self._set_fitted(True)
    return self

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 (B, T, F_in) or (N, F_in).

TYPE: Tensor

targets

Target matrix of shape (B, T, F_out) or (N, F_out).

TYPE: Tensor

RETURNS DESCRIPTION
RLSReadout

self, so calls can be chained.

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
@torch.no_grad()
def fit_online(self, states: torch.Tensor, targets: torch.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.

    Parameters
    ----------
    states : torch.Tensor
        State matrix of shape `(B, T, F_in)` or `(N, F_in)`.
    targets : torch.Tensor
        Target matrix of shape `(B, T, F_out)` or `(N, F_out)`.

    Returns
    -------
    RLSReadout
        `self`, so calls can be chained.
    """
    self.reset_state()
    return self.partial_fit(states, targets)

solve

solve(states: Tensor, targets: Tensor) -> tuple[Tensor, Tensor | None]

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 (N, in_features).

TYPE: Tensor

targets

Flattened target matrix of shape (N, out_features).

TYPE: Tensor

RETURNS DESCRIPTION
coefs

Coefficient matrix of shape (in_features, out_features).

TYPE: Tensor

intercept

Intercept vector of shape (out_features,), or None when the layer was built with bias=False.

TYPE: Tensor or None

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
def solve(
    self,
    states: torch.Tensor,
    targets: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor | None]:
    """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.

    Parameters
    ----------
    states : torch.Tensor
        Flattened state matrix of shape `(N, in_features)`.
    targets : torch.Tensor
        Flattened target matrix of shape `(N, out_features)`.

    Returns
    -------
    coefs : torch.Tensor
        Coefficient matrix of shape `(in_features, out_features)`.
    intercept : torch.Tensor or None
        Intercept vector of shape `(out_features,)`, or `None` when the
        layer was built with `bias=False`.
    """
    # The base ``fit`` has already flattened + validated, but reset the
    # recursion so a batch ``fit`` is a clean, order-independent restart.
    self.reset_state()
    self._rls_update(states, targets)
    self._set_fitted(True)
    # ``_rls_update`` already wrote the parameters; hand the base ``fit`` the
    # same values so its copy-back is a harmless no-op.
    coefs = self.weight.detach().T.to(states.dtype)
    intercept = None if self.bias is None else self.bias.detach().to(states.dtype)
    return coefs, intercept

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

\[ \min_W \; \lVert X W - Y \rVert_2^2 + \alpha\,\rho\,\lVert W \rVert_1 + \tfrac{1}{2}\,\alpha\,(1-\rho)\,\lVert W \rVert_2^2 \]

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

\[ \frac{1}{2 N} \lVert X w - y \rVert_2^2 + \alpha_{\mathrm{sk}}\,\rho\,\lVert w \rVert_1 + \tfrac{1}{2}\,\alpha_{\mathrm{sk}}\,(1-\rho)\,\lVert w \rVert_2^2 , \]

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

\[ \alpha_{\text{resdag}} = 2 N \, \alpha_{\mathrm{sk}} , \]

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

\[ L = 2\,\lambda_{\max}(X^\top X) + \alpha\,(1-\rho) , \]

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

out_features

Size of output features (prediction dimension).

TYPE: int

bias

Whether to include a bias term. When True the data is centered and an unpenalised intercept is recovered; when False the raw normal equations are used with no intercept.

TYPE: bool DEFAULT: True

name

Name for this readout layer. Used for identification in multi-readout architectures and as the key into targets by ESNTrainer.

TYPE: str DEFAULT: None

trainable

If True, weights are trainable via backpropagation.

TYPE: bool DEFAULT: False

alpha

Overall regularisation strength (must be non-negative). See the parameterisation note above for the relation to sklearn's alpha. alpha == 0 reduces to ordinary least squares (via FISTA).

TYPE: float DEFAULT: 1e-3

l1_ratio

Elastic-net mixing in [0, 1]. 1.0 is pure lasso, 0.0 is pure ridge, values in between blend the two.

TYPE: float DEFAULT: 1.0

max_iter

Maximum number of FISTA iterations.

TYPE: int DEFAULT: 1000

tol

Relative-change convergence tolerance on the coefficient matrix. A run that reaches max_iter without meeting it emits a RuntimeWarning.

TYPE: float DEFAULT: 1e-6

use_float64

If True the iteration runs in float64 and the result is cast back to the parameter dtype.

TYPE: bool DEFAULT: True

gram_dtype

Dtype for forming the Gram matrix and right-hand side (the heavy (N, F) matmuls). Default None forms the Gram in the solve dtype (float64 unless use_float64=False) on every device; pass torch.float32 to opt into faster, lower-precision GPU Gram formation.

TYPE: dtype DEFAULT: None

power_iters

If > 0, estimate the top Gram eigenvalue with this many power iterations instead of the exact torch.linalg.eigvalsh. The estimate is scaled up by (1 + power_iter_margin) to initialize the step size. Backtracking verifies the quadratic majorizer before each update; the margin alone is not a guaranteed spectral upper bound.

TYPE: int DEFAULT: 0

power_iter_margin

Initial margin applied to a power-iteration eigenvalue estimate.

TYPE: float DEFAULT: 0.05

ATTRIBUTE DESCRIPTION
weight

Weight matrix of shape (out_features, in_features).

TYPE: Parameter

bias

Bias vector of shape (out_features,), or None if bias=False.

TYPE: Parameter or None

alpha

Overall regularisation strength.

TYPE: float

l1_ratio

Elastic-net mixing parameter.

TYPE: float

n_iter_

Number of FISTA iterations run by the last fit (0 before the first fit).

TYPE: int

converged_

Whether the last fit met the tol stopping criterion.

TYPE: bool

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
def __init__(
    self,
    in_features: int,
    out_features: int,
    bias: bool = True,
    name: str | None = None,
    trainable: bool = False,
    *,
    alpha: float = 1e-3,
    l1_ratio: float = 1.0,
    max_iter: int = 1000,
    tol: float = 1e-6,
    use_float64: bool = True,
    gram_dtype: torch.dtype | None = None,
    power_iters: int = 0,
    power_iter_margin: float = 0.05,
) -> None:
    super().__init__(in_features, out_features, bias, name, trainable)
    if alpha < 0:
        raise ValueError(f"alpha must be non-negative, got {alpha}.")
    if not 0.0 <= l1_ratio <= 1.0:
        raise ValueError(f"l1_ratio must be in [0, 1], got {l1_ratio}.")
    if max_iter < 1:
        raise ValueError(f"max_iter must be >= 1, got {max_iter}.")
    if tol < 0:
        raise ValueError(f"tol must be non-negative, got {tol}.")
    if power_iters < 0:
        raise ValueError(f"power_iters must be non-negative, got {power_iters}.")
    if power_iter_margin < 0:
        raise ValueError(f"power_iter_margin must be non-negative, got {power_iter_margin}.")
    self.alpha = alpha
    self.l1_ratio = l1_ratio
    self.max_iter = max_iter
    self.tol = tol
    self.use_float64 = use_float64
    self.gram_dtype = gram_dtype
    self.power_iters = power_iters
    self.power_iter_margin = power_iter_margin
    # Diagnostics populated by solve.
    self.n_iter_: int = 0
    self.converged_: bool = False

solve

solve(states: Tensor, targets: Tensor) -> tuple[Tensor, Tensor | None]

Solve the elastic-net readout via FISTA on flattened inputs.

PARAMETER DESCRIPTION
states

Flattened state matrix of shape (N, in_features).

TYPE: Tensor

targets

Flattened target matrix of shape (N, out_features).

TYPE: Tensor

RETURNS DESCRIPTION
coefs

Coefficient matrix of shape (in_features, out_features).

TYPE: Tensor

intercept

Intercept vector of shape (out_features,), or None when the layer was built with bias=False.

TYPE: Tensor or None

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
def solve(
    self,
    states: torch.Tensor,
    targets: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor | None]:
    """Solve the elastic-net readout via FISTA on flattened inputs.

    Parameters
    ----------
    states : torch.Tensor
        Flattened state matrix of shape `(N, in_features)`.
    targets : torch.Tensor
        Flattened target matrix of shape `(N, out_features)`.

    Returns
    -------
    coefs : torch.Tensor
        Coefficient matrix of shape `(in_features, out_features)`.
    intercept : torch.Tensor or None
        Intercept vector of shape `(out_features,)`, or `None` when the
        layer was built with `bias=False`.
    """
    problem = build_ridge_problem(
        states,
        targets,
        fit_intercept=self.bias is not None,
        use_float64=self.use_float64,
        gram_dtype=self.gram_dtype,
    )

    # FISTA only needs the (centered) Gram and Xᵀy: the gradient of the
    # smooth part is 2·gram·W - 2·rhs + l2·W, so the O(N F) design matrix
    # never re-enters the loop. ``build_ridge_problem`` already folded the
    # (un-penalised) intercept centering into ``gram`` / ``rhs``, so the L1
    # penalty applied below acts only on the slopes — never the intercept.
    gram = problem.gram  # (F, F), solve dtype
    rhs = problem.rhs  # (F, T), solve dtype

    l1 = self.alpha * self.l1_ratio
    l2 = self.alpha * (1.0 - self.l1_ratio)

    lambda_max = self._top_eigenvalue(gram)
    lipschitz = 2.0 * lambda_max + l2
    if not math.isfinite(lipschitz):
        raise RuntimeError(
            "FISTA requires finite curvature; scale the features or use float64."
        )
    # Degenerate Gram (all-zero states / zero features): nothing to solve.
    if lipschitz <= 0.0:
        self.n_iter_ = 0
        self.converged_ = True
        coefs = torch.zeros_like(rhs)
        return finalize_fit(problem, coefs)

    upper_bound = lipschitz
    if self.power_iters > 0:
        upper_bound = (2.0 * float(gram.abs().sum(dim=1).max().item()) + l2) * (
            1.0 + 64 * torch.finfo(gram.dtype).eps
        )

    w = torch.zeros_like(rhs)
    z = w.clone()
    t = 1.0

    layer_name = (
        f"{type(self).__name__}('{self._name}')"
        if self._name is not None
        else type(self).__name__
    )

    converged = False
    n_iter = 0
    for k in range(self.max_iter):
        n_iter = k + 1
        # Gradient of the smooth part f at z: 2(gram·z - rhs) + l2·z.
        grad = 2.0 * (gram @ z - rhs)
        if l2 != 0.0:
            grad = grad + l2 * z
        # Proximal gradient step + soft-threshold (prox of the L1 term).
        while True:
            step = 1.0 / lipschitz
            w_new = _soft_threshold(z - step * grad, step * l1)
            if self.power_iters <= 0:
                break
            delta_z = w_new - z
            norm_squared = delta_z.square().sum()
            curvature = 2.0 * (delta_z * (gram @ delta_z)).sum() + l2 * norm_squared
            majorizer = lipschitz * norm_squared
            finite = torch.isfinite(curvature) & torch.isfinite(majorizer)
            if bool(finite & (curvature <= majorizer * (1 + 32 * torch.finfo(gram.dtype).eps))):
                break
            if lipschitz >= upper_bound or not math.isfinite(upper_bound):
                raise RuntimeError(
                    "FISTA could not form a finite safe step; scale features/targets "
                    "or use a higher working precision."
                )
            lipschitz = min(2.0 * lipschitz, upper_bound)

        # Nesterov momentum extrapolation.
        t_new = 0.5 * (1.0 + math.sqrt(1.0 + 4.0 * t * t))
        z = w_new + ((t - 1.0) / t_new) * (w_new - w)

        # Relative-change stopping criterion.
        w_norm = torch.linalg.norm(w)
        delta = torch.linalg.norm(w_new - w)
        w = w_new
        t = t_new
        if w_norm > 0:
            if float((delta / w_norm).item()) < self.tol:
                converged = True
                break
        elif float(delta.item()) < self.tol:
            # W is still (near) zero — the iterate has settled at the
            # origin (e.g. a penalty large enough to zero every weight).
            converged = True
            break

    self.n_iter_ = n_iter
    self.converged_ = converged
    if not converged:
        warnings.warn(
            f"{layer_name}: FISTA did not converge in max_iter={self.max_iter} "
            f"iterations (relative change still >= tol={self.tol:g}). The fitted "
            f"weights are the last iterate. Increase max_iter, loosen tol, or "
            f"raise alpha for a better-conditioned problem.",
            RuntimeWarning,
            stacklevel=3,
        )

    return finalize_fit(problem, w)

FISTAReadout

FISTAReadout(*args: Any, **kwargs: Any)

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
def __init__(self, *args: Any, **kwargs: Any) -> None:
    warnings.warn(
        "FISTAReadout is deprecated and will be removed in a future release; "
        "use FISTAReadoutLayer instead.",
        DeprecationWarning,
        stacklevel=2,
    )
    super().__init__(*args, **kwargs)

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 ([x, x**2]).

FeaturePartitioner

Partitions input features into overlapping groups.

NLAT2

T₂ nonlinear algebraic transform (x[i-1] * x[i-2] at even features).

NLAT3

T₃ nonlinear algebraic transform (x[i-1] * x[i+1] at interior even features).

Pad

Appends a constant column to the feature dimension ([x, padding]).

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; index=0, exponent=2 is the T₁/NLAT1 transform).

Standardize

Per-feature z-score standardization with buffer-stored mean/std, fit, and an exact inverse.

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

forward(*inputs: Tensor) -> Tensor

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: Tensor DEFAULT: ()

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
def forward(self, *inputs: torch.Tensor) -> torch.Tensor:
    """
    Concatenate input tensors along the last dimension.

    Parameters
    ----------
    *inputs : torch.Tensor
        Variable number of input tensors to concatenate. All tensors
        must have the same shape except for the last dimension.

    Returns
    -------
    torch.Tensor
        Concatenated tensor with combined feature dimension.

    Raises
    ------
    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])
    """
    return torch.cat(inputs, dim=-1)

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.

\[ \vec{x} = \{x_1, x_2, \dots, x_N, x_1^2, x_2^2, \dots, x_N^2\} \]

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

forward(input: Tensor) -> Tensor

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 (..., features).

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Tensor of shape (..., 2 * features) — the original features followed by their elementwise squares. Gradients flow through both blocks (the squared block contributes 2 * x to each feature's gradient) and stay finite for every real input.

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
def forward(self, input: torch.Tensor) -> torch.Tensor:
    """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.

    Parameters
    ----------
    input : torch.Tensor
        Tensor of shape `(..., features)`.

    Returns
    -------
    torch.Tensor
        Tensor of shape `(..., 2 * features)` — the original features
        followed by their elementwise squares. Gradients flow through both
        blocks (the squared block contributes `2 * x` to each feature's
        gradient) and stay finite for every real input.
    """
    return torch.cat([input, input * input], dim=-1)

FeaturePartitioner

FeaturePartitioner(partitions: int, overlap: int)

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
def __init__(self, partitions: int, overlap: int) -> None:
    """Initialize the FeaturePartitioner.

    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.
    """
    super().__init__()
    if partitions < 1:
        raise ValueError(f"partitions must be a positive integer, got {partitions}")
    if overlap < 0:
        raise ValueError(f"overlap must be a non-negative integer, got {overlap}")
    if partitions == 1 and overlap > 0:
        warnings.warn(
            f"FeaturePartitioner: overlap={overlap} is ignored when partitions == 1; "
            f"the single-partition fast path returns the input unchanged.",
            stacklevel=2,
        )

    self.partitions = partitions
    self.overlap = overlap

forward

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

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
def forward(self, input: torch.Tensor) -> list[torch.Tensor]:
    """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
    """
    # If partitions == 1, just return the entire input as a single partition
    if self.partitions == 1:
        return [input]

    features = input.shape[-1]

    # Validate shape
    if features % self.partitions != 0:
        raise ValueError(
            f"Feature dimension ({features}) must be divisible by "
            f"number of partitions ({self.partitions})"
        )

    partition_base_width = features // self.partitions

    if self.overlap >= partition_base_width:
        raise ValueError(
            f"Overlap ({self.overlap}) must be smaller than the base partition "
            f"width ({partition_base_width})"
        )

    # Width of each partition including overlap
    partition_width = partition_base_width + 2 * self.overlap

    # Circular wrapping
    if self.overlap > 0:
        # Concatenate: [last overlap features | all features | first overlap features]
        wrapped_input = torch.cat(
            [input[..., -self.overlap :], input, input[..., : self.overlap]],
            dim=-1,
        )
    else:
        wrapped_input = input

    # Extract partitions
    partitions_out = []
    for i in range(self.partitions):
        start = i * partition_base_width
        end = start + partition_width
        partitions_out.append(wrapped_input[..., start:end])

    return partitions_out

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.

\[ \tilde{x}_i = \begin{cases} x_{i-1}\, x_{i-2}, & i \ge 2 \text{ and } i \text{ even (0-based)}; \\ x_i, & \text{otherwise}. \end{cases} \]

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

forward(input: Tensor) -> Tensor

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 (..., features).

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Same shape as input; selected features hold the neighbour product x[i-1] * x[i-2], the rest are unchanged. Gradients are finite everywhere (each product is bilinear in the inputs).

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
def forward(self, input: torch.Tensor) -> torch.Tensor:
    """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.

    Parameters
    ----------
    input : torch.Tensor
        Tensor of shape `(..., features)`.

    Returns
    -------
    torch.Tensor
        Same shape as *input*; selected features hold the neighbour product
        `x[i-1] * x[i-2]`, the rest are unchanged. Gradients are finite
        everywhere (each product is bilinear in the inputs).
    """
    num_features = input.shape[-1]
    if num_features < 3:
        return input

    # prod[..., j] = x[..., j+1] * x[..., j] for j in 0..N-3, which are the
    # products x[i-1] * x[i-2] aligned to output positions i = 2..N-1. Pad
    # two zeros at the front so it lines up with feature indices 0..N-1.
    prod = input[..., 1:-1] * input[..., :-2]
    prod = torch.nn.functional.pad(prod, (2, 0))

    idx = _feature_parity_mask(num_features, input.device)
    mask = (idx >= 2) & (idx % 2 == 0)
    return torch.where(mask, prod, input)

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.

\[ \tilde{x}_i = \begin{cases} x_{i-1}\, x_{i+1}, & 2 \le i \le N-2 \text{ and } i \text{ even (0-based)}; \\ x_i, & \text{otherwise}. \end{cases} \]

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

forward(input: Tensor) -> Tensor

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 (..., features).

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Same shape as input; selected interior features hold the neighbour product x[i-1] * x[i+1], the rest are unchanged. Gradients are finite everywhere (each product is bilinear in the inputs).

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
def forward(self, input: torch.Tensor) -> torch.Tensor:
    """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.

    Parameters
    ----------
    input : torch.Tensor
        Tensor of shape `(..., features)`.

    Returns
    -------
    torch.Tensor
        Same shape as *input*; selected interior features hold the neighbour
        product `x[i-1] * x[i+1]`, the rest are unchanged. Gradients are
        finite everywhere (each product is bilinear in the inputs).
    """
    num_features = input.shape[-1]
    if num_features < 3:
        return input

    # prod[..., j] = x[..., j] * x[..., j+2] for j in 0..N-3, which are the
    # products x[i-1] * x[i+1] aligned to output positions i = 1..N-2. Pad
    # one zero at each end so it lines up with feature indices 0..N-1.
    prod = input[..., :-2] * input[..., 2:]
    prod = torch.nn.functional.pad(prod, (1, 1))

    idx = _feature_parity_mask(num_features, input.device)
    mask = (idx >= 2) & (idx <= num_features - 2) & (idx % 2 == 0)
    return torch.where(mask, prod, input)

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.

\[ \tilde{x} = \begin{bmatrix} x \\ \text{padding} \end{bmatrix} \]

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: float DEFAULT: 1.0

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: float DEFAULT: 1.0

Source code in src/resdag/layers/transforms/pad.py
51
52
53
54
55
56
57
58
59
60
def __init__(self, padding: float = 1.0) -> None:
    """Store the constant padding value appended in the forward pass.

    Parameters
    ----------
    padding : float, default=1.0
        Constant value appended as the trailing feature.
    """
    super().__init__()
    self.padding = padding

forward

forward(input: Tensor) -> Tensor

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 (..., features).

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Tensor of shape (..., features + 1) with a constant padding column appended. Gradients flow through the original features unchanged; the constant column carries no gradient.

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
def forward(self, input: torch.Tensor) -> torch.Tensor:
    """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*.

    Parameters
    ----------
    input : torch.Tensor
        Tensor of shape `(..., features)`.

    Returns
    -------
    torch.Tensor
        Tensor of shape `(..., features + 1)` with a constant `padding`
        column appended. Gradients flow through the original features
        unchanged; the constant column carries no gradient.
    """
    pad_shape = (*input.shape[:-1], 1)
    pad_column = input.new_full(pad_shape, self.padding)
    return torch.cat([input, pad_column], dim=-1)

PartialSquare

PartialSquare(eta: float | int)

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.

\[ g(x_i) = \begin{cases} x_i^2, & \text{if } i < k, \\ x_i, & \text{if } i \ge k. \end{cases} \]

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 float in (0, 1], the fraction of leading features to square: k = floor(eta * F) is resolved per call against the runtime feature count. If an int, the count of leading features to square directly (k = eta, clamped to F).

TYPE: float or int

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 float in (0, 1] (fraction of leading features to square) or a non-negative int (count of leading features to square).

TYPE: float or int

RAISES DESCRIPTION
ValueError

If eta is a float outside (0, 1] or a negative int.

TypeError

If eta is neither an int nor a float (bool is rejected — it is an int subclass but a nonsensical selector).

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
def __init__(self, eta: float | int) -> None:
    """Store and validate the fraction or count of leading features squared.

    Parameters
    ----------
    eta : float or int
        A `float` in `(0, 1]` (fraction of leading features to square)
        or a non-negative `int` (count of leading features to square).

    Raises
    ------
    ValueError
        If `eta` is a `float` outside `(0, 1]` or a negative `int`.
    TypeError
        If `eta` is neither an `int` nor a `float` (`bool` is
        rejected — it is an `int` subclass but a nonsensical selector).
    """
    super().__init__()
    # bool is an int subclass; reject it explicitly so True/False cannot
    # silently be read as the counts 1/0.
    if isinstance(eta, bool) or not isinstance(eta, (int, float)):
        raise TypeError(
            f"eta must be an int count or a float fraction, got {type(eta).__name__}"
        )

    self._is_fraction = isinstance(eta, float)
    if self._is_fraction:
        if not (0.0 < eta <= 1.0):
            raise ValueError(f"float eta must be in the interval (0, 1], got {eta}")
    else:
        if eta < 0:
            raise ValueError(f"int eta (feature count) must be non-negative, got {eta}")

    self.eta = eta

forward

forward(input: Tensor) -> Tensor

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 (..., features).

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Same shape as input; the first k features are squared, the remaining features are unchanged. Gradients are finite everywhere (x * x has gradient 2 * x on the squared block and 1 on the pass-through block).

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
def forward(self, input: torch.Tensor) -> torch.Tensor:
    """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.

    Parameters
    ----------
    input : torch.Tensor
        Tensor of shape `(..., features)`.

    Returns
    -------
    torch.Tensor
        Same shape as *input*; the first `k` features are squared, the
        remaining features are unchanged. Gradients are finite everywhere
        (`x * x` has gradient `2 * x` on the squared block and `1` on
        the pass-through block).
    """
    num_features = input.shape[-1]
    k = self._threshold(num_features)
    indices = torch.arange(num_features, device=input.device)
    mask = indices < k
    return torch.where(mask, input * input, input)

Power

Power(exponent: float, sign_preserving: bool = False)

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

sign_preserving

If True, every element uses the sign-preserving power sign(x) * abs(x) ** exponent. This keeps the forward and backward passes finite for negative bases under a non-integer exponent (e.g. tanh reservoir states in [-1, 1], which include negatives and zeros). If False (default), elements use plain torch.pow, whose real-valued result is nan for a negative base raised to a non-integer exponent, and inf for a zero base raised to a negative exponent.

TYPE: bool DEFAULT: False

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 nan in both the forward and backward pass (the real pow is 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: float

sign_preserving

If True, apply sign(x) * abs(x) ** exponent so negative bases stay finite under a non-integer exponent.

TYPE: bool DEFAULT: False

Source code in src/resdag/layers/transforms/power.py
68
69
70
71
72
73
74
75
76
77
78
79
80
81
def __init__(self, exponent: float, sign_preserving: bool = False) -> None:
    """Store the exponent and sign-preservation mode for the forward pass.

    Parameters
    ----------
    exponent : float
        Value the input is raised to for every element.
    sign_preserving : bool, default=False
        If `True`, apply `sign(x) * abs(x) ** exponent` so negative
        bases stay finite under a non-integer exponent.
    """
    super().__init__()
    self.exponent = exponent
    self.sign_preserving = sign_preserving

forward

forward(input: Tensor) -> Tensor

Raise the input to self.exponent.

PARAMETER DESCRIPTION
input

Tensor of shape (batch, ..., features).

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Same shape as input, with each element raised to exponent. When sign_preserving is set, sign(x) * abs(x) ** exponent is used, which is finite for negative bases under a non-integer exponent (where plain torch.pow returns nan).

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
def forward(self, input: torch.Tensor) -> torch.Tensor:
    """Raise the input to `self.exponent`.

    Parameters
    ----------
    input : torch.Tensor
        Tensor of shape `(batch, ..., features)`.

    Returns
    -------
    torch.Tensor
        Same shape as *input*, with each element raised to `exponent`.
        When `sign_preserving` is set, `sign(x) * abs(x) ** exponent` is
        used, which is finite for negative bases under a non-integer
        exponent (where plain `torch.pow` returns `nan`).
    """
    if self.sign_preserving:
        return input.sign() * input.abs().pow(self.exponent)
    return torch.pow(input, self.exponent)

SelectiveDropout

SelectiveDropout(mask: Sequence[bool] | ndarray | Tensor)

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
def __init__(self, mask: Sequence[bool] | np.ndarray | torch.Tensor) -> None:
    """Initialize the SelectiveDropout layer.

    Args:
        mask: Boolean mask indicating which features to zero out (True = drop)

    Raises:
        ValueError: If mask is not 1-dimensional
    """
    super().__init__()

    # Convert to torch tensor
    if isinstance(mask, torch.Tensor):
        mask_tensor = mask.bool()
    else:
        mask_tensor = torch.tensor(mask, dtype=torch.bool)

    # Validate shape
    if mask_tensor.ndim != 1:
        raise ValueError(f"Mask must be 1D, but got shape {mask_tensor.shape}")

    # Register as buffer (non-trainable, but part of state_dict)
    self.register_buffer("mask", mask_tensor)

forward

forward(input: Tensor) -> Tensor

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
def forward(self, input: torch.Tensor) -> torch.Tensor:
    """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
    """
    if input.dim() not in (2, 3):
        raise ValueError(
            f"SelectiveDropout expects 2D (batch, features) or 3D "
            f"(batch, timesteps, features) input, got {input.dim()}D tensor "
            f"with shape {input.shape}"
        )

    mask = cast(torch.Tensor, self.mask)
    feature_dim = input.shape[-1]
    if mask.shape[0] != feature_dim:
        raise ValueError(
            f"Mask size ({mask.shape[0]}) does not match feature dimension ({feature_dim})"
        )

    # Apply mask: where mask is True, output 0; otherwise keep input
    return torch.where(mask, torch.zeros_like(input), input)

SelectiveExponentiation

SelectiveExponentiation(index: int, exponent: float, sign_preserving: bool = False)

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 index targets even indices; odd index targets odd indices.

TYPE: int

exponent

Power applied to the selected positions.

TYPE: float

sign_preserving

If True, selected positions use the sign-preserving power sign(x) * abs(x) ** exponent. This keeps the forward and backward passes finite for negative selected bases under a non-integer exponent (e.g. tanh reservoir states in [-1, 1]). If False (default), selected positions use plain torch.pow, whose real-valued result is nan for a negative base with a non-integer exponent.

TYPE: bool DEFAULT: False

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

exponent

Power applied to selected positions.

TYPE: float

sign_preserving

If True, apply sign(x) * abs(x) ** exponent at selected positions so negative bases stay finite under a non-integer exponent.

TYPE: bool DEFAULT: False

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
def __init__(self, index: int, exponent: float, sign_preserving: bool = False) -> None:
    """Store parity selector, exponent, and sign-preservation mode.

    Parameters
    ----------
    index : int
        Determines which feature indices are exponentiated (even vs odd).
    exponent : float
        Power applied to selected positions.
    sign_preserving : bool, default=False
        If `True`, apply `sign(x) * abs(x) ** exponent` at selected
        positions so negative bases stay finite under a non-integer
        exponent.
    """
    super().__init__()
    self.index = index
    self.exponent = exponent
    self.sign_preserving = sign_preserving
    # Whether ``where(mask, x * x, x)`` reproduces the forward and gradient
    # exactly: only for a plain (non-sign-preserving) integer square. ``x * x``
    # is bit-identical to ``pow(x, 2)`` and finite for every real base, so the
    # safe-base masking is redundant there.
    self._is_square = (not sign_preserving) and float(exponent) == 2.0
    # Boolean parity masks cached per (feature_dim, device). Rebuilt lazily on
    # a new dim/device. Kept out of state_dict / named_buffers on purpose.
    self._mask_cache: dict[tuple[int, torch.device], torch.Tensor] = {}

forward

forward(input: Tensor) -> Tensor

Apply selective exponentiation along the last dimension.

PARAMETER DESCRIPTION
input

Tensor of shape (batch, ..., features).

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Same shape as input; selected indices are raised to exponent, others are unchanged. Gradients at unselected positions are always finite; selected positions are finite when sign_preserving is set or the base/exponent combination is real-valued.

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
def forward(self, input: torch.Tensor) -> torch.Tensor:
    """Apply selective exponentiation along the last dimension.

    Parameters
    ----------
    input : torch.Tensor
        Tensor of shape `(batch, ..., features)`.

    Returns
    -------
    torch.Tensor
        Same shape as *input*; selected indices are raised to `exponent`,
        others are unchanged. Gradients at unselected positions are always
        finite; selected positions are finite when `sign_preserving` is
        set or the base/exponent combination is real-valued.
    """
    mask = self._get_mask(input.shape[-1], input.device)

    # Fast path: a plain integer square is finite for every real base, so the
    # gate reduces to ``where(mask, x * x, x)``. This is bit-identical to the
    # safe-base path in both forward and gradient (``x * x == pow(x, 2)``) and
    # skips the ``ones_like`` allocation and the extra ``where``/``pow`` nodes.
    if self._is_square:
        return torch.where(mask, input * input, input)

    # General path. Feed a safe constant (1.0) into ``pow`` at unselected
    # positions so the pow node never evaluates a value that would
    # back-propagate as 0 * nan through torch.where (e.g. a negative
    # unselected base with a fractional exponent). pow(1, e) == 1 with a
    # finite gradient, and the where gate discards this branch for unselected
    # positions anyway.
    safe_base = torch.where(mask, input, torch.ones_like(input))

    if self.sign_preserving:
        powed = safe_base.sign() * safe_base.abs().pow(self.exponent)
    else:
        powed = safe_base.pow(self.exponent)

    return torch.where(mask, powed, input)

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

mean

Initial per-feature mean of shape (num_features,). Defaults to zeros (no centering until fit is called).

TYPE: Tensor DEFAULT: None

std

Finite, nonnegative initial standard deviation of shape (num_features,). Defaults to ones (no scaling until fit is called).

TYPE: Tensor DEFAULT: None

eps

Numerical-stability floor added to std before dividing. Guards against division by zero on constant features.

TYPE: float DEFAULT: 1e-8

ATTRIBUTE DESCRIPTION
mean

Registered buffer holding the per-feature mean (num_features,).

TYPE: Tensor

std

Registered buffer holding the per-feature standard deviation (num_features,).

TYPE: Tensor

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

mean

Initial per-feature mean of shape (num_features,) (default zeros).

TYPE: Tensor DEFAULT: None

std

Initial per-feature standard deviation of shape (num_features,) (default ones).

TYPE: Tensor DEFAULT: None

eps

Stability floor added to std before dividing.

TYPE: float DEFAULT: 1e-8

RAISES DESCRIPTION
ValueError

If num_features is not positive, or if a supplied mean/ std has the wrong shape, nonfinite values, or conflicting devices; also if std or eps is negative, or eps is nonfinite.

TypeError

If a supplied statistic is complex or eps is not a real number.

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
def __init__(
    self,
    num_features: int,
    mean: torch.Tensor | None = None,
    std: torch.Tensor | None = None,
    eps: float = 1e-8,
) -> None:
    """Register the per-feature mean/std buffers and the `eps` floor.

    Parameters
    ----------
    num_features : int
        Size of the feature dimension to standardize.
    mean : torch.Tensor, optional
        Initial per-feature mean of shape `(num_features,)` (default
        zeros).
    std : torch.Tensor, optional
        Initial per-feature standard deviation of shape
        `(num_features,)` (default ones).
    eps : float, default=1e-8
        Stability floor added to `std` before dividing.

    Raises
    ------
    ValueError
        If `num_features` is not positive, or if a supplied `mean`/
        `std` has the wrong shape, nonfinite values, or conflicting
        devices; also if `std` or `eps` is negative, or `eps` is
        nonfinite.
    TypeError
        If a supplied statistic is complex or `eps` is not a real number.
    """
    super().__init__()

    if num_features <= 0:
        raise ValueError(f"num_features must be positive, got {num_features}")
    try:
        finite_eps = math.isfinite(eps)
    except TypeError as error:
        raise TypeError("eps must be a finite, nonnegative real number") from error
    if not finite_eps or eps < 0:
        raise ValueError("eps must be finite and nonnegative")
    if isinstance(mean, torch.Tensor) and isinstance(std, torch.Tensor):
        if mean.device != std.device:
            raise ValueError("mean and std must be on the same device; move them explicitly")

    self.num_features = num_features
    self.eps = float(eps)

    # Constructor inputs, including inference tensors, must become ordinary
    # detached buffers so a later differentiable forward can save them.
    with torch.inference_mode(False), torch.no_grad():
        mean_stat = self._validate_stat(mean, "mean")
        std_stat = self._validate_stat(std, "std")
        provided = [stat for stat in (mean_stat, std_stat) if stat is not None]
        dtype = provided[0].dtype if provided else torch.get_default_dtype()
        for stat in provided[1:]:
            dtype = torch.promote_types(dtype, stat.dtype)
        tensor_stats = [stat for stat in (mean, std) if isinstance(stat, torch.Tensor)]
        device = tensor_stats[0].device if tensor_stats else torch.get_default_device()
        mean_buffer = (
            torch.zeros(num_features, dtype=dtype, device=device)
            if mean_stat is None
            else mean_stat.to(device=device, dtype=dtype).detach().clone()
        )
        std_buffer = (
            torch.ones(num_features, dtype=dtype, device=device)
            if std_stat is None
            else std_stat.to(device=device, dtype=dtype).detach().clone()
        )

    self.register_buffer("mean", mean_buffer)
    self.register_buffer("std", std_buffer)

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 (..., num_features) whose last dimension matches num_features.

TYPE: Tensor

RETURNS DESCRIPTION
Standardize

self, so calls can be chained (e.g. layer.fit(x)(x)).

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
@torch.no_grad()
def fit(self, input: torch.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.

    Parameters
    ----------
    input : torch.Tensor
        Data of shape `(..., num_features)` whose last dimension matches
        `num_features`.

    Returns
    -------
    Standardize
        `self`, so calls can be chained (e.g. `layer.fit(x)(x)`).

    Raises
    ------
    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.
    """
    if not isinstance(input, torch.Tensor):
        raise TypeError("Standardize.fit requires a torch.Tensor")
    if not input.is_floating_point():
        raise TypeError("Standardize.fit requires a real floating-point tensor")
    if input.ndim == 0 or input.numel() == 0:
        raise ValueError("Standardize.fit requires non-empty data with a feature dimension")
    if input.shape[-1] != self.num_features:
        raise ValueError(
            f"input feature dim ({input.shape[-1]}) does not match "
            f"num_features ({self.num_features})"
        )

    if input.device.type == "meta":
        raise ValueError("Standardize.fit requires concrete data, not a meta tensor")
    if not bool(torch.isfinite(input).all()):
        raise ValueError("Standardize.fit requires finite training values")
    with torch.inference_mode(False), torch.no_grad():
        flat = input.detach().reshape(-1, self.num_features)
        mean = flat.mean(dim=0)
        std = flat.std(dim=0, unbiased=False)
        if not bool(torch.isfinite(mean).all()) or not bool(torch.isfinite(std).all()):
            raise ValueError("Standardize statistics overflowed; use a higher training dtype")
        mean, std = mean.detach().clone(), std.detach().clone()
    self.mean, self.std = mean, std
    return self

forward

forward(input: Tensor) -> Tensor

Standardize the last dimension as (x - mean) / (std + eps).

PARAMETER DESCRIPTION
input

Tensor of shape (..., num_features).

TYPE: Tensor

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

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
def forward(self, input: torch.Tensor) -> torch.Tensor:
    """Standardize the last dimension as `(x - mean) / (std + eps)`.

    Parameters
    ----------
    input : torch.Tensor
        Tensor of shape `(..., num_features)`.

    Returns
    -------
    torch.Tensor
        Same shape as *input*, centered and scaled per feature. Gradients
        propagate through the input using the constant stored statistics.

    Raises
    ------
    ValueError
        If the last dimension of *input* does not equal `num_features`.
    """
    if input.shape[-1] != self.num_features:
        raise ValueError(
            f"input feature dim ({input.shape[-1]}) does not match "
            f"num_features ({self.num_features})"
        )
    return (input - self.mean) / self._scale()

inverse

inverse(input: Tensor) -> Tensor

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 (..., num_features).

TYPE: Tensor

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

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
@torch.jit.export
def inverse(self, input: torch.Tensor) -> torch.Tensor:
    """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.

    Parameters
    ----------
    input : torch.Tensor
        Standardized tensor of shape `(..., num_features)`.

    Returns
    -------
    torch.Tensor
        Same shape as *input*, mapped back to the original feature scale.

    Raises
    ------
    ValueError
        If the last dimension of *input* does not equal `num_features`.
    """
    if input.shape[-1] != self.num_features:
        raise ValueError(
            f"input feature dim ({input.shape[-1]}) does not match "
            f"num_features ({self.num_features})"
        )
    return input * self._scale() + self.mean