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:
- Reset reservoir states
- Traverse the complete warmup and training prefix once per graph node
- Fit each readout on training rows before forwarding its full prefix
- 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
TYPE:
|
| ATTRIBUTE | DESCRIPTION |
|---|---|
model |
The ESN model being trained.
TYPE:
|
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 | |
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:
TYPE:
|
train_inputs
|
Training sequences for fitting.
Format:
TYPE:
|
targets
|
Dictionary mapping readout name to target tensor.
For a single readout, pass the target tensor directly.
Each target shape:
TYPE:
|
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). |
noise_draws
|
When |
noise_seed
|
Seed for the explicit-noise ( |
| 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 |
TypeError
|
If |
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 | |
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
TYPE:
|
chunks
|
An iterable yielding
TYPE:
|
| 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 |
RuntimeError
|
If |
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 | |
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.
- 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 vectorr_t(reservoir state, possibly concatenated with the input, exactly as the graph presents it). - RLS-update the readout toward
d_tusingr_t— the a-priori errord_t - W_t^\top r_tdrives a rank-1 update ofWand the inverse-correlation matrixP(seeRLSReadout). - Recompute the output
z_{t+1} = W_{t+1}^\top r_twith 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
TYPE:
|
targets
|
The pattern to generate, shape
TYPE:
|
forgetting
|
Overrides the readout's forgetting factor \(\lambda \in (0, 1]\)
for this pass.
TYPE:
|
delta
|
Overrides the readout's \(P_0 = I / \delta\) prior for this pass.
TYPE:
|
initial_feedback
|
Feedback of shape
TYPE:
|
reset
|
If
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The closed-loop training outputs of shape |
| RAISES | DESCRIPTION |
|---|---|
TypeError
|
If the model's readout is not an |
ValueError
|
If the model has more than one readout (FORCE trains a single
generator readout), if |
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
RLSReadoutand itsout_featuresmust 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 | |
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
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 | |
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 | |