Skip to content

Reference

Training

ESNTrainer fits raw ESNModel graphs with each readout's configured solver. Its fit method processes the complete warmup-plus-training prefix in dependency order: a readout is fitted before its output reaches a downstream reservoir. Each reservoir consumes the continuous prefix once. Use Model.fit or ESN.fit when you also need training-only scaling, named signals and original units; see the common workflow.

For long streams, fit_stream accepts chunks and incremental ridge readouts, then finalizes their accumulated statistics. fit_force trains a single RLS head inside the autonomous feedback loop. Direct online fitting is available on RLSReadout.fit_online, not as another trainer method. See streaming and training for these distinct lifecycles.

Calibration functions change reservoir operating points using observed training inputs and return a CalibrationReport. They are explicit steps, separate from readout fitting and default model construction.

training

ESN Training Utilities

This module provides trainers for ESN models that fit readout layers algebraically using ridge regression, rather than stochastic gradient descent.

CLASS DESCRIPTION
ESNTrainer

Trainer for fitting readout layers in ESN models.

Examples:

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

resdag.layers.readouts.CGReadoutLayer : Readout with CG solver. resdag.core.ESNModel : ESN model class.

ESNTrainer

ESNTrainer(model: ESNModel)

Trainer for ESN models with algebraic readout fitting.

This trainer fits all ReadoutLayer instances in an ESN model using algebraic methods (e.g., ridge regression) rather than gradient descent. Pre-hooks fit each readout using its supervised training rows before it evaluates the complete prefix. Downstream reservoirs therefore receive fitted upstream predictions throughout warmup and training.

The training process:

  1. Reset reservoir states
  2. Traverse the complete warmup and training prefix once per graph node
  3. Fit each readout on training rows before forwarding its full prefix
  4. Reuse branches and release feature tensors after their last consumer

Each readout handles its own fitting hyperparameters (e.g., alpha for ridge regression is set during layer construction).

PARAMETER DESCRIPTION
model

ESN model to train. Must contain at least one ReadoutLayer.

TYPE: ESNModel

ATTRIBUTE DESCRIPTION
model

The ESN model being trained.

TYPE: ESNModel

Examples:

Basic training workflow:

>>> from resdag.training import ESNTrainer
>>> from resdag.core import ESNModel
>>>
>>> trainer = ESNTrainer(model)
>>> trainer.fit(
...     warmup_inputs=(warmup_data,),
...     train_inputs=(train_data,),
...     targets={"output": train_targets},
... )

Training with driving inputs:

>>> trainer.fit(
...     warmup_inputs=(warmup_feedback, warmup_driver),
...     train_inputs=(train_feedback, train_driver),
...     targets={"output": targets},
... )

Multi-readout training:

>>> trainer.fit(
...     warmup_inputs=(warmup_data,),
...     train_inputs=(train_data,),
...     targets={
...         "position": position_targets,
...         "velocity": velocity_targets,
...     },
... )
See Also

ESNModel : ESN model class. CGReadoutLayer : Conjugate gradient readout layer. ESNModel.forecast : Forecasting after training.

Notes
  • Warmup and training data must have the same number of input tensors.
  • Training data and targets must have the same sequence length.
  • Target keys must match readout names (user-defined or auto-generated).
Source code in src/resdag/training/trainer.py
124
125
def __init__(self, model: ESNModel) -> None:
    self.model = model

fit

fit(
    warmup_inputs: InputStreams,
    train_inputs: InputStreams,
    targets: ReadoutTargets,
    *,
    state_noise: float = 0.0,
    noise_draws: int | None = None,
    noise_seed: int | None = None
) -> None

Fit all readouts in one complete-prefix graph traversal.

Uses pre-hooks to fit each readout layer just before its forward method executes. This ensures downstream layers receive outputs from already-fitted readouts.

Warmup and training inputs are concatenated into owned storage. Each reservoir consumes that prefix once, carrying state continuously across the boundary. Each readout fits only its training features, then applies its fitted mapping to both warmup and training before downstream nodes run. Temporal layers see the complete prefix too. Declare recurrent dependencies as separate functional graph nodes or through standard torch.nn.Sequential containers. Opaque custom modules containing both readouts and reservoirs cannot be ordered safely.

Ordinary model, container and layer hooks run once on the full prefix. Removing the former discarded stage replays also changes stochastic layers' draw sequence; noisy results can differ from the old trainer. The model's training modes and noise configuration are preserved.

PARAMETER DESCRIPTION
warmup_inputs

Warmup sequences for state synchronization. Format: (feedback, driver1, driver2, ...). Each tensor shape: (batch, warmup_steps, features).

TYPE: torch.Tensor or sequence of torch.Tensor

train_inputs

Training sequences for fitting. Format: (feedback, driver1, driver2, ...). Each tensor shape: (batch, train_steps, features). Must have same sequence length as targets.

TYPE: torch.Tensor or sequence of torch.Tensor

targets

Dictionary mapping readout name to target tensor. For a single readout, pass the target tensor directly. Each target shape: (batch, train_steps, out_features). Names are either user-defined (via name="output" in readout constructor) or auto-generated module names (e.g., "CGReadoutLayer_1").

TYPE: torch.Tensor or dict of str to torch.Tensor

state_noise

Standard deviation \(\sigma\) of the Gaussian state noise the readouts are regularised with — a standard, tunable tool for closed-loop (autonomous-rollout) robustness. Fitting on noise-perturbed reservoir states mimics the feedback error the model sees when it free-runs on its own output, trading a little one-step accuracy for closed-loop stability (Jaeger's state noise; Wikner et al. 2024, Stabilizing machine learning prediction of dynamics, Chaos 34, 043105). 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). 0.0 (default) leaves every fit byte-identical to a plain ridge solve. Applied for the duration of this fit call by temporarily setting each ridge-family readout's state_noise (restored afterwards), so the model's configured readouts are not permanently mutated.

TYPE: (float, keyword - only) DEFAULT: 0.0

noise_draws

When state_noise > 0: None (default) uses the closed-form LMNT term (one solve of the expected noisy normal equations); an integer M >= 1 averages the Gram matrices and right-hand sides of M explicit noisy-state draws, then solves once (Monte-Carlo). This does not average separately fitted weights. Ignored when state_noise == 0.

TYPE: (int, keyword - only) DEFAULT: None

noise_seed

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

TYPE: (int, keyword - only) DEFAULT: None

RAISES DESCRIPTION
ValueError

If no warmup or training inputs provided. If number of warmup and training inputs don't match. If any readout is missing from targets. If target sequence length doesn't match training inputs. If state_noise is negative or noise_draws < 1.

TypeError

If state_noise > 0 but a readout in the model does not support state-noise regularisation (only the ridge-family direct solvers — RidgeReadoutLayer, CholeskyReadoutLayer — carry a state_noise knob).

Notes

After calling fit(), all readouts will have is_fitted=True and the model is ready for inference or forecasting.

Emits a UserWarning if targets dict contains names not matching any readout.

Examples:

>>> trainer = ESNTrainer(model)
>>> trainer.fit(
...     warmup_inputs=(warmup_data,),
...     train_inputs=(train_data,),
...     targets={"output": targets},
... )
>>> print(model.CGReadoutLayer_1.is_fitted)
True

Regularise for a stable chaotic rollout with closed-form LMNT noise:

>>> trainer.fit(
...     warmup_inputs=(warmup_data,),
...     train_inputs=(train_data,),
...     targets={"output": targets},
...     state_noise=1e-3,
... )
Source code in src/resdag/training/trainer.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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
def fit(
    self,
    warmup_inputs: InputStreams,
    train_inputs: InputStreams,
    targets: ReadoutTargets,
    *,
    state_noise: float = 0.0,
    noise_draws: int | None = None,
    noise_seed: int | None = None,
) -> None:
    r"""
    Fit all readouts in one complete-prefix graph traversal.

    Uses pre-hooks to fit each readout layer just before its forward
    method executes. This ensures downstream layers receive outputs
    from already-fitted readouts.

    Warmup and training inputs are concatenated into owned storage. Each
    reservoir consumes that prefix once, carrying state continuously across
    the boundary. Each readout fits only its training features, then applies
    its fitted mapping to both warmup and training before downstream nodes
    run. Temporal layers see the complete prefix too. Declare recurrent
    dependencies as separate functional graph nodes or through
    standard `torch.nn.Sequential` containers. Opaque custom modules
    containing both readouts and reservoirs cannot be ordered safely.

    Ordinary model, container and layer hooks run once on the full prefix.
    Removing the former discarded stage replays also changes stochastic
    layers' draw sequence; noisy results can differ from the old trainer.
    The model's training modes and noise configuration are preserved.

    Parameters
    ----------
    warmup_inputs : torch.Tensor or sequence of torch.Tensor
        Warmup sequences for state synchronization.
        Format: `(feedback, driver1, driver2, ...)`.
        Each tensor shape: `(batch, warmup_steps, features)`.
    train_inputs : torch.Tensor or sequence of torch.Tensor
        Training sequences for fitting.
        Format: `(feedback, driver1, driver2, ...)`.
        Each tensor shape: `(batch, train_steps, features)`.
        Must have same sequence length as targets.
    targets : torch.Tensor or dict of str to torch.Tensor
        Dictionary mapping readout name to target tensor.
        For a single readout, pass the target tensor directly.
        Each target shape: `(batch, train_steps, out_features)`.
        Names are either user-defined (via `name="output"` in readout
        constructor) or auto-generated module names (e.g., `"CGReadoutLayer_1"`).
    state_noise : float, keyword-only, default=0.0
        Standard deviation $\sigma$ of the Gaussian **state noise** the
        readouts are regularised with — a standard, tunable tool for
        **closed-loop (autonomous-rollout) robustness**.  Fitting on
        noise-perturbed reservoir states mimics the feedback error the model
        sees when it free-runs on its own output, trading a little one-step
        accuracy for closed-loop stability (Jaeger's state noise; Wikner et
        al. 2024, *Stabilizing machine learning prediction of dynamics*, Chaos
        34, 043105).  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).  `0.0`
        (default) leaves every fit byte-identical to a plain ridge solve.
        Applied for the duration of this `fit` call by temporarily setting
        each ridge-family readout's `state_noise` (restored afterwards), so
        the model's configured readouts are not permanently mutated.
    noise_draws : int, keyword-only, optional
        When `state_noise > 0`: `None` (default) uses the closed-form
        **LMNT** term (one solve of the expected noisy normal equations); an
        integer `M >= 1` averages the Gram matrices and right-hand sides
        of `M` explicit noisy-state draws, then solves once (Monte-Carlo).
        This does not average separately fitted weights. Ignored when
        `state_noise == 0`.
    noise_seed : int, keyword-only, optional
        Seed for the explicit-noise (`noise_draws`) draws, for
        reproducibility.  Ignored for the deterministic LMNT path.

    Raises
    ------
    ValueError
        If no warmup or training inputs provided.
        If number of warmup and training inputs don't match.
        If any readout is missing from targets.
        If target sequence length doesn't match training inputs.
        If `state_noise` is negative or `noise_draws < 1`.
    TypeError
        If `state_noise > 0` but a readout in the model does not support
        state-noise regularisation (only the ridge-family direct solvers —
        `RidgeReadoutLayer`, `CholeskyReadoutLayer` — carry a
        `state_noise` knob).

    Notes
    -----
    After calling `fit()`, all readouts will have `is_fitted=True` and the model is ready for inference or forecasting.

    Emits a `UserWarning` if targets dict contains names not matching any readout.

    Examples
    --------
    >>> trainer = ESNTrainer(model)
    >>> trainer.fit(
    ...     warmup_inputs=(warmup_data,),
    ...     train_inputs=(train_data,),
    ...     targets={"output": targets},
    ... )
    >>> print(model.CGReadoutLayer_1.is_fitted)
    True

    Regularise for a stable chaotic rollout with closed-form LMNT noise:

    >>> trainer.fit(  # doctest: +SKIP
    ...     warmup_inputs=(warmup_data,),
    ...     train_inputs=(train_data,),
    ...     targets={"output": targets},
    ...     state_noise=1e-3,
    ... )
    """
    warmup_inputs = self._input_tuple(warmup_inputs)
    train_inputs = self._input_tuple(train_inputs)
    if len(warmup_inputs) == 0:
        raise ValueError("At least one warmup input is required")
    if len(train_inputs) == 0:
        raise ValueError("At least one training input is required")
    if len(warmup_inputs) != len(train_inputs):
        raise ValueError(
            f"warmup_inputs has {len(warmup_inputs)} tensors, "
            f"but train_inputs has {len(train_inputs)} tensors. Must match."
        )
    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}.")

    # Resolve readouts once; reuse for target validation and hook setup.
    readouts = self._discover_readouts()
    targets = self._target_dict(targets, readouts)
    self._validate_targets(targets, readouts)
    targets = {name: targets[name] for name, _ in readouts}

    self._validate_input_shapes(warmup_inputs, label="warmup_inputs")
    self._validate_input_shapes(
        train_inputs, label="train_inputs", targets=targets, readouts=readouts
    )
    if warmup_inputs[0].shape[0] != train_inputs[0].shape[0]:
        raise ValueError("warmup_inputs and train_inputs must have the same batch size")
    train_steps = train_inputs[0].shape[1]

    # Validate target shapes
    readout_names = [name for name, _ in readouts]
    for name in readout_names:
        target = targets[name]
        if target.shape[1] != train_steps:
            raise ValueError(
                f"Target for '{name}' has {target.shape[1]} timesteps, "
                f"but train_inputs has {train_steps} timesteps. Must match."
            )

    # Concatenation owns the input storage, protecting caller data even if
    # a custom graph operation mutates its input before a later fit fails.
    with torch.no_grad():
        prefix = tuple(
            torch.cat((warm, train), dim=1) for warm, train in zip(warmup_inputs, train_inputs)
        )
    self._fit_complete_prefix(
        prefix,
        targets,
        fit_start=warmup_inputs[0].shape[1],
        state_noise=state_noise,
        noise_draws=noise_draws,
        noise_seed=noise_seed,
        owned=True,
        readouts=readouts,
    )

fit_stream

fit_stream(warmup_inputs: InputStreams, chunks: Iterable[StreamChunk]) -> None

Fit IncrementalRidgeReadoutLayer readouts over a stream of chunks.

The streaming counterpart of fit. Instead of fitting from one in-memory (B, T, F) block, it warms the reservoir once and then consumes chunks one at a time — e.g. windows yielded by a torch.utils.data.DataLoader — accumulating each readout's ridge sufficient statistics with resdag.layers.IncrementalRidgeReadoutLayer.partial_fit and solving once at the end with resdag.layers.IncrementalRidgeReadoutLayer.finalize. No more than a single chunk's states are ever held in memory, which is what lets a sequence too long to materialise — or one streamed off disk — be fitted.

Because the reservoir is stateful, the chunks must be contiguous in time and in order: state flows from the end of one chunk into the start of the next, exactly as it would in a single long forward pass. Shuffling the chunks would desynchronise the reservoir and is not supported.

Readouts must be independent: a readout downstream of another readout needs a separate fitting pass and is rejected. Every readout must be an resdag.layers.IncrementalRidgeReadoutLayer (the only readout with a partial_fit / finalize interface). The accumulators are reset at the start, so calling fit_stream again re-fits from scratch.

PARAMETER DESCRIPTION
warmup_inputs

Warmup sequences for state synchronization, format (feedback, driver1, ...), each of shape (batch, warmup_steps, features). The reservoir is reset before this pass (as in fit).

TYPE: tuple of torch.Tensor

chunks

An iterable yielding (inputs, targets) per chunk. inputs is an input tuple (feedback, driver1, ...) of the same arity as warmup_inputs; targets maps each readout name to its target tensor of shape (batch, chunk_steps, out_features). Consumed lazily, so a generator or DataLoader never materialises the whole sequence.

TYPE: iterable of (tuple of torch.Tensor, dict of str to torch.Tensor)

RAISES DESCRIPTION
ValueError

If no warmup inputs are provided, if a chunk's input arity does not match the warmup arity, if any readout is missing from a chunk's targets, or if a target's sequence length does not match its chunk's input length, or if readouts depend on other readouts.

TypeError

If any readout in the model is not an IncrementalRidgeReadoutLayer.

RuntimeError

If chunks is empty (no statistics were accumulated, so there is nothing to finalize).

Notes

After fit_stream returns, every readout has is_fitted=True and the model is ready for inference or forecasting.

Examples:

>>> from resdag.layers import IncrementalRidgeReadoutLayer
>>> trainer = ESNTrainer(model)  # model uses IncrementalRidgeReadoutLayer
>>> def chunk_stream():
...     for x, y in dataloader:  # contiguous windows
...         yield (x,), {"output": y}
>>> trainer.fit_stream(
...     warmup_inputs=(warmup_data,),
...     chunks=chunk_stream(),
... )
See Also

fit : Single-pass in-memory fitting. resdag.layers.IncrementalRidgeReadoutLayer : The streaming readout.

Source code in src/resdag/training/trainer.py
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
def fit_stream(
    self,
    warmup_inputs: InputStreams,
    chunks: Iterable[StreamChunk],
) -> None:
    """Fit `IncrementalRidgeReadoutLayer` readouts over a stream of chunks.

    The streaming counterpart of `fit`. Instead of fitting from one
    in-memory `(B, T, F)` block, it warms the reservoir once and then
    consumes `chunks` one at a time — e.g. windows yielded by a
    `torch.utils.data.DataLoader` — accumulating each readout's ridge
    sufficient statistics with
    `resdag.layers.IncrementalRidgeReadoutLayer.partial_fit` and solving
    once at the end with
    `resdag.layers.IncrementalRidgeReadoutLayer.finalize`. No more than a
    single chunk's states are ever held in memory, which is what lets a
    sequence too long to materialise — or one streamed off disk — be fitted.

    Because the reservoir is stateful, the chunks must be **contiguous in
    time and in order**: state flows from the end of one chunk into the
    start of the next, exactly as it would in a single long forward pass.
    Shuffling the chunks would desynchronise the reservoir and is not
    supported.

    Readouts must be independent: a readout downstream of another readout
    needs a separate fitting pass and is rejected. Every readout must be an
    `resdag.layers.IncrementalRidgeReadoutLayer` (the only readout with a
    `partial_fit` / `finalize` interface). The accumulators are reset at
    the start, so calling `fit_stream` again re-fits from scratch.

    Parameters
    ----------
    warmup_inputs : tuple of torch.Tensor
        Warmup sequences for state synchronization, format
        `(feedback, driver1, ...)`, each of shape
        `(batch, warmup_steps, features)`. The reservoir is reset before
        this pass (as in `fit`).
    chunks : iterable of (tuple of torch.Tensor, dict of str to torch.Tensor)
        An iterable yielding `(inputs, targets)` per chunk. `inputs` is
        an input tuple `(feedback, driver1, ...)` of the same arity as
        `warmup_inputs`; `targets` maps each readout name to its target
        tensor of shape `(batch, chunk_steps, out_features)`. Consumed
        lazily, so a generator or `DataLoader` never materialises the whole
        sequence.

    Raises
    ------
    ValueError
        If no warmup inputs are provided, if a chunk's input arity does not
        match the warmup arity, if any readout is missing from a chunk's
        targets, or if a target's sequence length does not match its chunk's
        input length, or if readouts depend on other readouts.
    TypeError
        If any readout in the model is not an `IncrementalRidgeReadoutLayer`.
    RuntimeError
        If `chunks` is empty (no statistics were accumulated, so there is
        nothing to finalize).

    Notes
    -----
    After `fit_stream` returns, every readout has `is_fitted=True` and
    the model is ready for inference or forecasting.

    Examples
    --------
    >>> from resdag.layers import IncrementalRidgeReadoutLayer
    >>> trainer = ESNTrainer(model)  # model uses IncrementalRidgeReadoutLayer
    >>> def chunk_stream():
    ...     for x, y in dataloader:  # contiguous windows  # doctest: +SKIP
    ...         yield (x,), {"output": y}
    >>> trainer.fit_stream(  # doctest: +SKIP
    ...     warmup_inputs=(warmup_data,),
    ...     chunks=chunk_stream(),
    ... )

    See Also
    --------
    fit : Single-pass in-memory fitting.
    resdag.layers.IncrementalRidgeReadoutLayer : The streaming readout.
    """
    warmup_inputs = self._input_tuple(warmup_inputs)
    if len(warmup_inputs) == 0:
        raise ValueError("At least one warmup input is required")

    readouts = self._discover_readouts()
    non_incremental = [
        name for name, ro in readouts if not isinstance(ro, IncrementalRidgeReadoutLayer)
    ]
    if non_incremental:
        raise TypeError(
            f"fit_stream() requires every readout to be an IncrementalRidgeReadoutLayer, "
            f"but these are not: {non_incremental}. Use fit() for single-pass readouts, "
            f"or rebuild the model with IncrementalRidgeReadoutLayer."
        )

    self.model._get_execution_plan(require_explicit_state=False)
    self._validate_stream_dependencies()
    self._validate_input_shapes(warmup_inputs, label="warmup_inputs")

    # Reset accumulators so a re-fit starts clean, then warm up once. The
    # readouts are unfitted during warmup too, so let their forward flow a
    # value while the reservoir synchronises (shared with ``fit``).
    for _, readout in readouts:
        assert isinstance(readout, IncrementalRidgeReadoutLayer)
        readout.reset_accumulators()
    with self._allow_unfitted_warmup(readouts):
        self.model.warmup(*warmup_inputs)

    # Per-chunk: register pre-hooks that accumulate sufficient statistics
    # for each readout, then run a forward pass that carries the reservoir
    # state forward into the next chunk.
    n_chunks = 0
    for inputs, targets in chunks:
        inputs = self._input_tuple(inputs)
        targets = self._target_dict(targets, readouts)
        if len(inputs) != len(warmup_inputs):
            raise ValueError(
                f"Chunk {n_chunks} has {len(inputs)} input tensors, but warmup_inputs "
                f"has {len(warmup_inputs)}. Must match."
            )
        self._validate_targets(targets, readouts)
        self._validate_input_shapes(
            inputs, label=f"Chunk {n_chunks}", targets=targets, readouts=readouts
        )
        if inputs[0].shape[0] != warmup_inputs[0].shape[0]:
            raise ValueError(
                f"Chunk {n_chunks} batch size must match warmup_inputs; contiguous "
                "streams must keep the same trajectories in every batch slot."
            )
        chunk_steps = inputs[0].shape[1]

        hooks: list[torch.utils.hooks.RemovableHandle] = []
        for name, readout in readouts:
            target = targets[name]
            if target.shape[1] != chunk_steps:
                for h in hooks:
                    h.remove()
                raise ValueError(
                    f"Target for '{name}' in chunk {n_chunks} has {target.shape[1]} "
                    f"timesteps, but the chunk inputs have {chunk_steps}. Must match."
                )

            def make_partial_fit_hook(
                layer: IncrementalRidgeReadoutLayer, tgt: torch.Tensor
            ) -> Callable[[torch.nn.Module, tuple[torch.Tensor, ...]], None]:
                def hook(module: torch.nn.Module, args: tuple[torch.Tensor, ...]) -> None:
                    layer.partial_fit(args[0], tgt)

                return hook

            assert isinstance(readout, IncrementalRidgeReadoutLayer)
            handle = readout.register_forward_pre_hook(make_partial_fit_hook(readout, target))
            hooks.append(handle)
            # The readout is unfitted during accumulation; its forward only
            # needs to flow a value downstream, so bypass the fitted guard.
            readout._allow_unfitted_forward = True

        try:
            with torch.no_grad():
                self.model(*inputs)
        finally:
            for h in hooks:
                h.remove()
            for _, readout in readouts:
                assert isinstance(readout, IncrementalRidgeReadoutLayer)
                readout._allow_unfitted_forward = False
        n_chunks += 1

    if n_chunks == 0:
        raise RuntimeError(
            "fit_stream() received no chunks; nothing was accumulated to finalize."
        )

    # Solve every readout once from its accumulated statistics.
    for _, readout in readouts:
        assert isinstance(readout, IncrementalRidgeReadoutLayer)
        readout.finalize()

fit_force

fit_force(
    warmup_inputs: InputStreams,
    targets: Tensor,
    *,
    forgetting: float | None = None,
    delta: float | None = None,
    initial_feedback: Tensor | None = None,
    reset: bool = True
) -> Tensor

FORCE-train the readout to autonomously generate a target pattern.

Implements FORCE learning (Sussillo & Abbott 2009, "Generating Coherent Patterns of Activity from Chaotic Neural Networks"): the reservoir is run closed-loop — driven at every step by the network's own readout output fed back as the next input — while the single resdag.layers.RLSReadout is updated online (one rank-1 RLS step per timestep) toward the target signal d_t at that step. Because the readout is trained inside the feedback loop it will actually run in, the fed-back output progressively locks onto the target; after training the network free-runs and reproduces the pattern autonomously.

When to use FORCE (honest scope)

FORCE's value is training the readout inside the closed loop, so its weights are fit against the states the loop actually visits rather than the teacher-forced states an open-loop fit sees. Its classic advantage is stabilising autonomous generation in regimes where an open-loop teacher-forced ridge fit would diverge in closed loop — high-dimensional or strongly chaotic reservoirs where teacher-forced and free-running state trajectories pull apart and open-loop errors compound.

It is not a free win over open-loop ridge in general. For a clean, low-dimensional periodic target trained over a long window, an open-loop teacher-forced ridge readout (fit) is already an excellent closed-loop generator — the smooth target leaves little error to compound — and ridge can be much more accurate than FORCE on such a target. FORCE's relative accuracy depends on the seed and problem. Reach for FORCE when the reservoir is chaotic enough that the open-loop free run is unstable, or when the target is non-stationary and you want the online / forgetting machinery of RLSReadout; for a stationary, easily-generated target, the simpler fit is often sufficient.

Per step t (after an optional teacher-forced warmup that settles the reservoir on the target):

The default bootstrap consumes the final observed warmup feedback once more as the first closed-loop input; the initially zero RLS readout cannot supply a useful seed. initial_feedback overrides this input. This training bootstrap differs from ESNModel.forecast, whose default returns the trained readout's immediate next-sample prediction.

  1. Feed the current feedback z_t (the network's own last output, or the warmup's for the first step) through the model, reading the readout's input feature vector r_t (reservoir state, possibly concatenated with the input, exactly as the graph presents it).
  2. RLS-update the readout toward d_t using r_t — the a-priori error d_t - W_t^\top r_t drives a rank-1 update of W and the inverse-correlation matrix P (see RLSReadout).
  3. Recompute the output z_{t+1} = W_{t+1}^\top r_t with the updated weights and feed it back as the next step's input.

The readout's RLS state (P and the weights) is reset at the start of the FORCE pass (via RLSReadout.reset_state) so a re-run trains from scratch; pass forgetting / delta to override the readout's recursion hyperparameters for the pass.

PARAMETER DESCRIPTION
warmup_inputs

Teacher-forced warmup driving the reservoir open-loop with the true signal to settle its state before the closed-loop FORCE phase. Format (feedback, driver1, ...); the feedback is typically the leading slice of the target series. Each tensor has shape (batch, warmup_steps, features). May be empty-length in time (warmup_steps == 0) to start FORCE from the reset state, but at least the feedback tensor must be present (its dtype/device/batch and the driver arity are read from it).

TYPE: tuple of torch.Tensor

targets

The pattern to generate, shape (batch, T, feedback_dim). Its feature dimension must equal the model's feedback input dimension (and the readout's out_features) — the autoregression contract, since the readout output is fed back as the next feedback. T is the number of closed-loop FORCE steps.

TYPE: Tensor

forgetting

Overrides the readout's forgetting factor \(\lambda \in (0, 1]\) for this pass. None (default) keeps the readout's configured value. FORCE is classically run with 1.0 (growing window).

TYPE: float DEFAULT: None

delta

Overrides the readout's \(P_0 = I / \delta\) prior for this pass. None (default) keeps the readout's configured value. A moderate delta (around 1.0) is the standard FORCE choice; a very small delta (huge initial P) makes the early closed-loop updates explode.

TYPE: float DEFAULT: None

initial_feedback

Feedback of shape (batch, 1, feedback_dim) seeding the first closed-loop step. If None (default) the last warmup target slice is used (or a zero seed when the warmup is empty).

TYPE: Tensor DEFAULT: None

reset

If True (default), reset the reservoir states before the teacher-forced warmup. Set False to continue from the current (already warmed) reservoir state.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
Tensor

The closed-loop training outputs of shape (batch, T, feedback_dim) — the network's own generated signal at each FORCE step, after that step's RLS update. By the end of training these track targets closely; free-run generation with ESNModel.forecast continues the pattern from the final reservoir state.

RAISES DESCRIPTION
TypeError

If the model's readout is not an RLSReadout (FORCE needs the online RLS partial_fit machinery).

ValueError

If the model has more than one readout (FORCE trains a single generator readout), if warmup_inputs is empty, if targets is not 3-D, if the readout's out_features (and hence the fed-back output dimension) does not match targets's feature dimension (the autoregression contract), if the driver arity of warmup_inputs does not match the model, or if initial_feedback has the wrong shape.

Notes
  • Single-readout, self-generating only. FORCE here trains exactly one readout whose output is fed straight back as the model's feedback, so the readout must be an RLSReadout and its out_features must equal the feedback dimension. Multi-readout or driven-generation setups are out of scope and rejected with a clear error.
  • Driven models. If the model has driver inputs, pass the driver warmup slices in warmup_inputs; during the closed-loop phase the drivers are held at their last warmup value (FORCE classically targets autonomous generation, not driven mapping). A feedback-only model is the common case.
  • Reservoir regime. FORCE works best with a chaotic reservoir (spectral radius > 1, e.g. 1.5); the online readout tames the chaos into the target pattern. See the module example.

Examples:

>>> from resdag.models import classic_esn
>>> from resdag import RLSReadout
>>> from resdag.training import ESNTrainer
>>> model = classic_esn(
...     600, feedback_size=1, output_size=1, spectral_radius=1.5,
...     readout=RLSReadout, readout_name="output", readout_bias=False,
... )
>>> trainer = ESNTrainer(model)
>>> trainer.fit_force(
...     warmup_inputs=(target[:, :200, :],),
...     targets=target[:, 200:, :],
...     delta=1.0,
... )
>>> generated = model.forecast(target, horizon=1000)
See Also

fit : Open-loop teacher-forced algebraic readout fitting. resdag.layers.RLSReadout : The online RLS readout FORCE drives. resdag.core.ESNModel.forecast : Free-run generation after FORCE training.

Source code in src/resdag/training/trainer.py
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
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
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
def fit_force(
    self,
    warmup_inputs: InputStreams,
    targets: torch.Tensor,
    *,
    forgetting: float | None = None,
    delta: float | None = None,
    initial_feedback: torch.Tensor | None = None,
    reset: bool = True,
) -> torch.Tensor:
    r"""FORCE-train the readout to autonomously *generate* a target pattern.

    Implements FORCE learning (Sussillo & Abbott 2009, "Generating Coherent
    Patterns of Activity from Chaotic Neural Networks"): the reservoir is run
    **closed-loop** — driven at every step by the network's *own* readout
    output fed back as the next input — while the single
    `resdag.layers.RLSReadout` is updated online (one rank-1 RLS step
    per timestep) toward the target signal `d_t` at that step.  Because the
    readout is trained *inside* the feedback loop it will actually run in, the
    fed-back output progressively locks onto the target; after training the
    network **free-runs** and reproduces the pattern autonomously.

    When to use FORCE (honest scope)
    --------------------------------
    FORCE's value is training the readout *inside the closed loop*, so its
    weights are fit against the states the loop actually visits rather than
    the teacher-forced states an open-loop fit sees. Its classic advantage is
    **stabilising autonomous generation in regimes where an open-loop
    teacher-forced ridge fit would diverge in closed loop** — high-dimensional
    or strongly chaotic reservoirs where teacher-forced and free-running state
    trajectories pull apart and open-loop errors compound.

    It is **not** a free win over open-loop ridge in general. For a *clean,
    low-dimensional periodic* target trained over a long window, an open-loop
    teacher-forced ridge readout (`fit`) is already an excellent
    closed-loop generator — the smooth target leaves little error to compound
    — and ridge can be much more accurate than FORCE on such a target.
    FORCE's relative accuracy depends on the seed and problem. Reach for
    FORCE when the reservoir is chaotic enough
    that the open-loop free run is unstable, or when the target is
    non-stationary and you want the online / forgetting machinery of
    `RLSReadout`; for a stationary, easily-generated target, the
    simpler `fit` is often sufficient.

    Per step `t` (after an optional teacher-forced warmup that settles the
    reservoir on the target):

    The default bootstrap consumes the final observed warmup feedback once
    more as the first closed-loop input; the initially zero RLS readout
    cannot supply a useful seed. `initial_feedback` overrides this input.
    This training bootstrap differs from `ESNModel.forecast`, whose
    default returns the trained readout's immediate next-sample prediction.

    1. Feed the current feedback `z_t` (the network's own last output, or
       the warmup's for the first step) through the model, reading the
       readout's input feature vector `r_t` (reservoir state, possibly
       concatenated with the input, exactly as the graph presents it).
    2. RLS-update the readout toward `d_t` using `r_t` — the a-priori
       error `d_t - W_t^\top r_t` drives a rank-1 update of `W` and the
       inverse-correlation matrix `P` (see `RLSReadout`).
    3. Recompute the output `z_{t+1} = W_{t+1}^\top r_t` with the *updated*
       weights and feed it back as the next step's input.

    The readout's RLS state (`P` and the weights) is reset at the start of
    the FORCE pass (via `RLSReadout.reset_state`) so a re-run trains
    from scratch; pass `forgetting` / `delta` to override the readout's
    recursion hyperparameters for the pass.

    Parameters
    ----------
    warmup_inputs : tuple of torch.Tensor
        Teacher-forced warmup driving the reservoir *open-loop* with the true
        signal to settle its state before the closed-loop FORCE phase.
        Format `(feedback, driver1, ...)`; the feedback is typically the
        leading slice of the target series.  Each tensor has shape
        `(batch, warmup_steps, features)`.  May be empty-length in time
        (`warmup_steps == 0`) to start FORCE from the reset state, but at
        least the feedback tensor must be present (its dtype/device/batch and
        the driver arity are read from it).
    targets : torch.Tensor
        The pattern to generate, shape `(batch, T, feedback_dim)`.  Its
        feature dimension **must** equal the model's feedback input dimension
        (and the readout's `out_features`) — the autoregression contract,
        since the readout output is fed back as the next feedback.  `T` is
        the number of closed-loop FORCE steps.
    forgetting : float, optional
        Overrides the readout's forgetting factor $\lambda \in (0, 1]$
        for this pass.  `None` (default) keeps the readout's configured
        value.  FORCE is classically run with `1.0` (growing window).
    delta : float, optional
        Overrides the readout's $P_0 = I / \delta$ prior for this pass.
        `None` (default) keeps the readout's configured value.  A moderate
        `delta` (around `1.0`) is the standard FORCE choice; a very small
        `delta` (huge initial `P`) makes the early closed-loop updates
        explode.
    initial_feedback : torch.Tensor, optional
        Feedback of shape `(batch, 1, feedback_dim)` seeding the first
        closed-loop step.  If `None` (default) the last warmup target slice
        is used (or a zero seed when the warmup is empty).
    reset : bool, default=True
        If `True` (default), reset the reservoir states before the
        teacher-forced warmup.  Set `False` to continue from the current
        (already warmed) reservoir state.

    Returns
    -------
    torch.Tensor
        The closed-loop training outputs of shape `(batch, T, feedback_dim)`
        — the network's own generated signal at each FORCE step, *after* that
        step's RLS update.  By the end of training these track `targets`
        closely; free-run generation with `ESNModel.forecast` continues
        the pattern from the final reservoir state.

    Raises
    ------
    TypeError
        If the model's readout is not an `RLSReadout` (FORCE needs the
        online RLS `partial_fit` machinery).
    ValueError
        If the model has more than one readout (FORCE trains a single
        generator readout), if `warmup_inputs` is empty, if `targets` is
        not 3-D, if the readout's `out_features` (and hence the fed-back
        output dimension) does not match `targets`'s feature dimension (the
        autoregression contract), if the driver arity of `warmup_inputs`
        does not match the model, or if `initial_feedback` has the wrong
        shape.

    Notes
    -----
    - **Single-readout, self-generating only.**  FORCE here trains exactly one
      readout whose output is fed straight back as the model's feedback, so
      the readout must be an `RLSReadout` and its `out_features` must equal
      the feedback dimension.  Multi-readout or driven-generation setups are
      out of scope and rejected with a clear error.
    - **Driven models.**  If the model has driver inputs, pass the driver
      warmup slices in `warmup_inputs`; during the closed-loop phase the
      drivers are held at their last warmup value (FORCE classically targets
      autonomous generation, not driven mapping).  A feedback-only model is
      the common case.
    - **Reservoir regime.**  FORCE works best with a *chaotic* reservoir
      (spectral radius `> 1`, e.g. `1.5`); the online readout tames the
      chaos into the target pattern.  See the module example.

    Examples
    --------
    >>> from resdag.models import classic_esn
    >>> from resdag import RLSReadout
    >>> from resdag.training import ESNTrainer
    >>> model = classic_esn(  # doctest: +SKIP
    ...     600, feedback_size=1, output_size=1, spectral_radius=1.5,
    ...     readout=RLSReadout, readout_name="output", readout_bias=False,
    ... )
    >>> trainer = ESNTrainer(model)  # doctest: +SKIP
    >>> trainer.fit_force(  # doctest: +SKIP
    ...     warmup_inputs=(target[:, :200, :],),
    ...     targets=target[:, 200:, :],
    ...     delta=1.0,
    ... )
    >>> generated = model.forecast(target, horizon=1000)  # doctest: +SKIP

    See Also
    --------
    fit : Open-loop teacher-forced algebraic readout fitting.
    resdag.layers.RLSReadout : The online RLS readout FORCE drives.
    resdag.core.ESNModel.forecast : Free-run generation after FORCE training.
    """
    warmup_inputs = self._input_tuple(warmup_inputs)
    if len(warmup_inputs) == 0:
        raise ValueError(
            "fit_force() requires at least one warmup input (the feedback tensor), "
            "even if it is length-0 in time; the model's dtype/device/batch and "
            "driver arity are read from it."
        )
    if targets.dim() != 3:
        raise ValueError(
            f"fit_force() targets must be 3-D (batch, T, feedback_dim); "
            f"got shape {tuple(targets.shape)}."
        )

    # FORCE trains exactly one online RLS readout whose output is the
    # generated signal fed straight back as feedback.
    readouts = self._discover_readouts()
    if len(readouts) != 1:
        names = [name for name, _ in readouts]
        raise ValueError(
            f"fit_force() trains a single self-generating readout, but the model has "
            f"{len(readouts)} readout(s): {names}. FORCE feeds one readout's output "
            f"straight back as the model feedback; multi-readout generation is out of "
            f"scope."
        )
    readout_name, readout = readouts[0]
    if not isinstance(readout, RLSReadout):
        raise TypeError(
            f"fit_force() requires the readout ('{readout_name}') to be an RLSReadout "
            f"(the online recursive-least-squares readout whose partial_fit drives the "
            f"FORCE update), but it is a {type(readout).__name__}. Rebuild the model "
            f"with readout=RLSReadout."
        )

    feedback_dim = targets.shape[-1]
    if readout.out_features != feedback_dim:
        raise ValueError(
            f"fit_force(): the readout ('{readout_name}') has out_features="
            f"{readout.out_features}, but targets have feedback_dim={feedback_dim}. "
            f"FORCE feeds the readout output back as the next feedback, so the readout "
            f"output dimension must equal the feedback (target) dimension."
        )

    num_drivers = len(warmup_inputs) - 1
    expected_drivers = len(self.model.inputs) - 1
    if num_drivers != expected_drivers:
        raise ValueError(
            f"fit_force(): the model has {expected_drivers} driver input(s) but "
            f"warmup_inputs carries {num_drivers}. Pass (feedback, driver1, ...) matching "
            f"the model's inputs."
        )

    self.model._get_execution_plan(require_explicit_state=False)
    self._validate_input_shapes(warmup_inputs, label="warmup_inputs")
    if targets.shape[0] != warmup_inputs[0].shape[0]:
        raise ValueError("fit_force(): targets and warmup_inputs must share batch size")
    if targets.device != warmup_inputs[0].device:
        raise ValueError("fit_force(): targets and warmup_inputs must share device")

    # Driven models hold each driver at its last warmup value during the
    # closed-loop phase, so an empty warmup leaves no value to hold.
    if num_drivers and warmup_inputs[0].shape[1] == 0:
        raise ValueError(
            "fit_force(): a driven model needs a non-empty warmup so each driver has a "
            "last value to hold during the autonomous closed-loop phase; the warmup "
            "feedback has 0 timesteps. Provide at least one warmup step."
        )

    batch_size = warmup_inputs[0].shape[0]
    device = warmup_inputs[0].device
    dtype = warmup_inputs[0].dtype

    if initial_feedback is not None:
        expected = (batch_size, 1, feedback_dim)
        if initial_feedback.dim() != 3 or tuple(initial_feedback.shape) != expected:
            raise ValueError(
                f"fit_force(): initial_feedback must have shape {expected} "
                f"(batch, 1, feedback_dim); got {tuple(initial_feedback.shape)}."
            )

    # Apply per-pass overrides, then reset the RLS recursion (P = I/delta,
    # zero weights) so a re-run trains from scratch.
    if forgetting is not None:
        if not 0.0 < forgetting <= 1.0:
            raise ValueError(
                f"fit_force(): forgetting (lambda) must be in (0, 1], got {forgetting}."
            )
        readout.forgetting = forgetting
    if delta is not None:
        if delta <= 0.0:
            raise ValueError(f"fit_force(): delta must be positive, got {delta}.")
        readout.delta = delta
    readout.reset_state()

    # Capture the readout's input feature vector each step via a pre-hook.
    # The normal graph forward (unlike the flat forecast engine) fires hooks,
    # so this sees exactly what the readout consumes — reservoir state,
    # concatenated input, etc. — regardless of the architecture upstream.
    captured: dict[str, torch.Tensor] = {}

    def _capture_hook(_module: torch.nn.Module, args: tuple[torch.Tensor, ...]) -> None:
        captured["features"] = args[0]

    handle = readout.register_forward_pre_hook(_capture_hook)

    total_steps = targets.shape[1]
    outputs = torch.empty(batch_size, total_steps, feedback_dim, dtype=dtype, device=device)

    # Drivers are held at their last warmup value during the closed-loop
    # phase (FORCE generates autonomously). Feedback-only models skip this.
    held_drivers: tuple[torch.Tensor, ...] = ()
    try:
        with torch.no_grad():
            # Phase 1: teacher-forced warmup, driving the reservoir open-loop
            # with the true signal. ``RLSReadout.forward`` is plain linear
            # (no fitted-guard, weights zero after reset_state), so it flows a
            # harmless zero downstream while the reservoir synchronises — the
            # warmup only needs the reservoir state, not the readout output.
            if warmup_inputs[0].shape[1] > 0:
                self.model.warmup(*warmup_inputs, reset=reset)
                seed = warmup_inputs[0][:, -1:, :]
            elif reset:
                self.model.reset_reservoirs()
                seed = torch.zeros(batch_size, 1, feedback_dim, dtype=dtype, device=device)
            else:
                seed = torch.zeros(batch_size, 1, feedback_dim, dtype=dtype, device=device)

            if num_drivers:
                held_drivers = tuple(d[:, -1:, :] for d in warmup_inputs[1:])

            if initial_feedback is not None:
                z = initial_feedback
            else:
                z = seed

            # Phase 2: closed-loop FORCE. Each step drives the model with the
            # network's own feedback, reads the readout feature vector, applies
            # one RLS update toward the target, and feeds the *updated* output
            # back into the next step.
            for t in range(total_steps):
                d = targets[:, t : t + 1, :]
                self.model(z, *held_drivers)
                features = captured["features"]
                readout.partial_fit(features, d)
                z = readout(features)
                outputs[:, t, :] = z.squeeze(1)
    finally:
        handle.remove()

    return outputs

CalibrationReport dataclass

CalibrationReport(
    method: str,
    epochs: int,
    steps: int,
    samples: int,
    activity_mean_before: float,
    activity_std_before: float,
    activity_mean_after: float,
    activity_std_after: float,
    spectral_radius_before: float | None = None,
    spectral_radius_after: float | None = None,
)

Small immutable summary of calibration, measured on the training inputs.

steps counts parameter updates (batch-averaged, not individual samples). Activity statistics pool all neurons and samples after warmup and are descriptive; a Gaussian target or a requested radius is not a guarantee of task accuracy. Radius fields are populated only for flow control.

calibrate_intrinsic_plasticity

calibrate_intrinsic_plasticity(
    reservoir: ESNLayer,
    training_inputs: Tensor | Sequence[Tensor],
    *,
    driver: Tensor | None = None,
    target_mean: float = 0.0,
    target_std: float = 0.1,
    learning_rate: float = 0.001,
    epochs: int = 1,
    warmup: int = 0,
    min_gain: float = 0.001,
    max_gain: float = 100.0
) -> CalibrationReport

Adapt tanh gains and offsets before fitting a readout.

Pass only training data, shaped (T, F) or (B, T, F). Supply a driver with driver=... or pass (feedback, driver). Each batch item starts from the configured initial state each epoch; warmup evolves the state without adapting. Noise is not applied, and there is no random sampling. Repeating the call on identically initialized layers is deterministic.

This is Gaussian-target intrinsic plasticity, with neuron output y=tanh(a*x+b) and the stochastic updates

\[ \Delta b=-\eta[-\mu/\sigma^2+(y/\sigma^2) (2\sigma^2+1-y^2+\mu y)],\quad \Delta a=\eta/a+\Delta b\,x. \]

For batched inputs updates are averaged over batch items. Gain clipping to [min_gain, max_gain] bounds unsafe updates. The target is approximate: bounded tanh outputs cannot realize an arbitrary Gaussian distribution. Reservoir weights remain fixed. Changes are committed only after a finite rollout succeeds; failure leaves weights, buffers, mode and state intact. Success clears the old recurrent state so the new dynamics start cleanly.

Reference: Verstraeten, Schrauwen & Stroobandt, Adapting reservoirs to get Gaussian distributions, ESANN 2007, equations 10–11.

Source code in src/resdag/training/calibration.py
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
@torch.no_grad()
def calibrate_intrinsic_plasticity(
    reservoir: ESNLayer,
    training_inputs: Tensor | Sequence[Tensor],
    *,
    driver: Tensor | None = None,
    target_mean: float = 0.0,
    target_std: float = 0.1,
    learning_rate: float = 1e-3,
    epochs: int = 1,
    warmup: int = 0,
    min_gain: float = 1e-3,
    max_gain: float = 100.0,
) -> CalibrationReport:
    r"""Adapt tanh gains and offsets before fitting a readout.

    Pass only training data, shaped `(T, F)` or `(B, T, F)`. Supply a driver
    with `driver=...` or pass `(feedback, driver)`. Each batch item starts
    from the configured initial state each epoch; `warmup` evolves the state
    without adapting. Noise is not applied, and there is no random sampling.
    Repeating the call on identically initialized layers is deterministic.

    This is Gaussian-target intrinsic plasticity, with neuron output
    `y=tanh(a*x+b)` and the stochastic updates

    $$
    \Delta b=-\eta[-\mu/\sigma^2+(y/\sigma^2)
      (2\sigma^2+1-y^2+\mu y)],\quad
    \Delta a=\eta/a+\Delta b\,x.
    $$

    For batched inputs updates are averaged over batch items. Gain clipping to
    `[min_gain, max_gain]` bounds unsafe updates. The target is approximate:
    bounded tanh outputs cannot realize an arbitrary Gaussian distribution.
    Reservoir weights remain fixed. Changes are committed only after a finite
    rollout succeeds; failure leaves weights, buffers, mode and state intact.
    Success clears the old recurrent state so the new dynamics start cleanly.

    Reference: Verstraeten, Schrauwen & Stroobandt, *Adapting reservoirs to get
    Gaussian distributions*, ESANN 2007, equations 10–11.
    """
    mean = _finite("target_mean", target_mean)
    std = _finite("target_std", target_std, positive=True)
    if abs(mean) >= 1 or std * std >= 1 - mean * mean:
        raise ValueError(
            "target_mean/target_std must describe feasible moments inside tanh's (-1, 1) range"
        )
    data = _prepare(
        reservoir, training_inputs, driver, warmup, epochs, learning_rate, min_gain, max_gain
    )
    if std * std < torch.finfo(data.cell.weight_hh.dtype).tiny:
        raise ValueError("target_std is too small for the reservoir dtype")
    gain = _buffer(data.cell, "_intrinsic_gain", 1.0)
    bias = _buffer(data.cell, "_intrinsic_bias", 0.0)
    recurrent_gain = _buffer(data.cell, "_recurrent_gain", 1.0)
    if not bool((gain > 0).all()):
        raise ValueError("intrinsic gains must be positive")
    before = _stats(data, gain, bias, recurrent_gain)
    finite = gain.new_tensor(True, dtype=torch.bool)
    variance = std * std
    for _ in range(epochs):
        state = data.initial_state.clone()
        for time in range(data.projected.shape[1]):
            raw = data.projected[:, time] + recurrent_gain * F.linear(state, data.cell.weight_hh)
            output = torch.tanh(gain * raw + bias)
            state = data.cell._apply_leak(state, output)
            if time < warmup:
                continue
            delta_bias = -data.rate * (
                -mean / variance
                + output / variance * (2 * variance + 1 - output.square() + mean * output)
            )
            next_gain = gain + data.rate / gain + (delta_bias * raw).mean(dim=0)
            next_bias = bias + delta_bias.mean(dim=0)
            finite &= torch.isfinite(next_gain).all() & torch.isfinite(next_bias).all()
            gain = next_gain.clamp(min_gain, max_gain)
            bias = next_bias
    if not bool(finite):
        raise RuntimeError("intrinsic plasticity diverged; reduce learning_rate or input scale")
    after = _stats(data, gain, bias, recurrent_gain)
    report = _report(data, "intrinsic_plasticity", before, after)
    data.cell._intrinsic_gain = gain.detach()
    data.cell._intrinsic_bias = bias.detach()
    data.cell._has_intrinsic = True
    reservoir.reset_state()
    return report

calibrate_flow_control

calibrate_flow_control(
    reservoir: ESNLayer,
    training_inputs: Tensor | Sequence[Tensor],
    *,
    driver: Tensor | None = None,
    target_radius: float = 0.9,
    learning_rate: float = 0.001,
    epochs: int = 1,
    warmup: int = 0,
    mode: Literal["local", "global"] = "local",
    min_gain: float = 0.001,
    max_gain: float = 100.0
) -> CalibrationReport

Adapt recurrent row gains using local or global flow control.

a <- a * (1 + learning_rate * (target_radius**2 * h_prev**2 - x_rec**2)) where x_rec=a*(W@h_prev). Updates average over batch items; global also averages over neurons, applying a shared multiplicative update. Input/feedback weights and bias are fixed. Gain clipping supplies numerical bounds. No eigenvalue calculation occurs in the adaptation loop; measured matrix radii are reported before/after as diagnostics.

This rule assumes unit-leak tanh dynamics with no intrinsic-plasticity transform. Unsupported combinations fail before mutation. Local control is approximate and can miss the requested radius for strongly correlated inputs or structured weights. A target radius is not a stability guarantee. Input shapes, warmup, state cleanup and transactional behavior match calibrate_intrinsic_plasticity.

Reference: Schubert & Gros (2021), Local homeostatic regulation of the spectral radius of echo-state networks, equations 5–6, https://arxiv.org/abs/2101.10665.

Source code in src/resdag/training/calibration.py
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
@torch.no_grad()
def calibrate_flow_control(
    reservoir: ESNLayer,
    training_inputs: Tensor | Sequence[Tensor],
    *,
    driver: Tensor | None = None,
    target_radius: float = 0.9,
    learning_rate: float = 1e-3,
    epochs: int = 1,
    warmup: int = 0,
    mode: Literal["local", "global"] = "local",
    min_gain: float = 1e-3,
    max_gain: float = 100.0,
) -> CalibrationReport:
    r"""Adapt recurrent row gains using local or global flow control.

    `a <- a * (1 + learning_rate * (target_radius**2 * h_prev**2 - x_rec**2))`
    where `x_rec=a*(W@h_prev)`. Updates average over batch items; `global`
    also averages over neurons, applying a shared multiplicative update.
    Input/feedback weights and bias are fixed. Gain clipping supplies numerical
    bounds. No eigenvalue calculation occurs in the adaptation loop; measured
    matrix radii are reported before/after as diagnostics.

    This rule assumes unit-leak tanh dynamics with no intrinsic-plasticity
    transform. Unsupported combinations fail before mutation. Local control is
    approximate and can miss the requested radius for strongly correlated
    inputs or structured weights. A target radius is not a stability guarantee.
    Input shapes, warmup, state cleanup and transactional behavior match
    `calibrate_intrinsic_plasticity`.

    Reference: Schubert & Gros (2021), *Local homeostatic regulation of the
    spectral radius of echo-state networks*, equations 5–6,
    https://arxiv.org/abs/2101.10665.
    """
    radius = _finite("target_radius", target_radius, positive=True)
    if mode not in ("local", "global"):
        raise ValueError("mode must be 'local' or 'global'")
    data = _prepare(
        reservoir, training_inputs, driver, warmup, epochs, learning_rate, min_gain, max_gain
    )
    leak = torch.as_tensor(data.cell.leak_rate)
    if not bool((leak == 1).all()):
        raise ValueError("flow control requires leak_rate=1")
    if data.cell._intrinsic_gain is not None:
        raise ValueError(
            "apply flow control before intrinsic plasticity, using an unadapted tanh activation"
        )
    weights = data.cell.weight_hh
    stored_values = weights.values() if weights.layout == torch.sparse_csr else weights
    if not bool((stored_values != 0).any()):
        raise ValueError("flow control cannot adapt an all-zero recurrent matrix")
    gain = _buffer(data.cell, "_recurrent_gain", 1.0)
    if not bool((gain > 0).all()):
        raise ValueError("recurrent gains must be positive")
    ones = gain.new_ones(gain.shape)
    zeros = gain.new_zeros(gain.shape)
    before = _stats(data, ones, zeros, gain)
    from resdag.layers.cells._compact_recurrent import _scale_recurrent_rows

    radius_before = estimate_spectral_radius(_scale_recurrent_rows(data.cell.weight_hh, gain))
    finite = gain.new_tensor(True, dtype=torch.bool)
    for _ in range(epochs):
        state = data.initial_state.clone()
        for time in range(data.projected.shape[1]):
            recurrent = gain * F.linear(state, data.cell.weight_hh)
            output = torch.tanh(data.projected[:, time] + recurrent)
            if time >= warmup:
                delta = (radius * radius * state.square() - recurrent.square()).mean(dim=0)
                if mode == "global":
                    delta = delta.mean()
                next_gain = gain * (1 + data.rate * delta)
                finite &= torch.isfinite(next_gain).all()
                gain = next_gain.clamp(min_gain, max_gain)
            state = output
    if not bool(finite):
        raise RuntimeError("flow control diverged; reduce learning_rate or input scale")
    after = _stats(data, ones, zeros, gain)
    radius_after = estimate_spectral_radius(_scale_recurrent_rows(data.cell.weight_hh, gain))
    report = _report(data, "flow_control", before, after, radius_before, radius_after)
    data.cell._recurrent_gain = gain.detach()
    data.cell._has_recurrent_gain = True
    reservoir.reset_state()
    return report