Reference
ESN preset¶
rd.ESN is a standard torch.nn.Module for a classic reservoir and readout.
It uses the same training-only scaling, original units, state handling and
forecast timing as Model.
import torch
import resdag as rd
series = torch.stack((torch.linspace(0, 8, 160).sin(),
torch.linspace(0, 8, 160).cos()), dim=-1)
esn = rd.ESN(reservoir_size=24, washout=10, seed=3).fit(series)
prediction = esn.forecast(horizon=20) # Tensor, (20, 2), original units
raw_graph = esn.graph # ESNModel, for already-normalized inputs
A 2-D input stays 2-D. A batched (batch, time, features) input keeps its batch
axis even when batch=1. Ordinary esn(x) carries state and retains gradients;
call esn.reset_state() between unrelated sequences. esn.forward_stateless(x)
returns predictions and explicit recurrent states without changing stored state.
prediction_lead sets the target's distance into the future. Its default
feedback delay follows that lead; explicit connections use the preset's
"input" and "output" ports. These controls and forecast(execution="history")
use the same rules as the common model workflow.
Build before attaching an optimizer¶
Pass input_size to build eagerly, or call build(width) before collecting
parameters. Otherwise the first successful fit infers the feature width.
pipeline_esn = rd.ESN(
reservoir_size=16, input_size=2, washout=10, seed=4,
readout_kwargs={"trainable": True},
).fit(series)
optimizer = torch.optim.Adam(pipeline_esn.parameters(), lr=1e-3)
pipeline_esn.reset_state()
batch = series[:8].detach().requires_grad_()
optimizer.zero_grad()
pipeline_esn(batch).square().mean().backward()
optimizer.step()
assert batch.grad is not None
The single registered esn.workflow child is a Model; .graph gives the raw
symbolic graph. Refitting preserves the existing parameter objects. Use
Model(inputs=..., outputs=...) for custom branches, drivers and multiple heads.
input_to_readout=True includes the current input alongside reservoir states
in the readout features. Set it to False for a head using reservoir memory
alone. The setting is a strict boolean and can be supplied before lazy building
or with input_size for eager construction. Automatic vanilla tuning tries
both values. A custom search_space replaces that search; an omitted setting
keeps the current recipe's value. Saving preserves the selected wiring.
input_transforms={"input": module} and output_transforms={"output": module}
override the preset's preprocessing per port. Supplied modules remain
registered while the preset is lazy, and successful building/fitting keeps
the original module and Parameter objects. A failed first fit leaves them
registered without attaching an incomplete workflow. Build before collecting
all model parameters for an optimizer. Custom modules use the reversible
protocol described in custom preprocessing.
Placement, solvers and checkpoints¶
An untouched lazy preset adopts the first floating tensor's device and dtype.
Explicit constructor settings and pre-build .to(...)/.double() conversions
fix the current placement. Later refits require matching tensors, as ordinary
PyTorch modules do. build(width, device=..., dtype=...) selects placement
explicitly; use .to(...) to move an already-built preset.
The default readout="auto" checks numerical safety and chooses a solve while
preserving the requested alpha. readout_kwargs configures it, for example
{"solver": "svd"} or {"solve_dtype": torch.float32, "cpu_fallback": False}.
Its last_solve report records the actual solver, working device/precision,
conditioning and any fallback. Native MPS fits use supported float32 operations;
an unsafe or unsupported solve warns before using CPU float64 unless fallback
was disabled. Fitted parameters and predictions remain on the model device.
See readout solvers for explicit alternatives and
their own keyword settings. Reservoir options and custom initializers continue
to pass through the preset.
A matching preset can restore a state_dict before its input width is built.
Checkpoint metadata validates preset architecture settings before weight copies;
scaling, observed history and trajectory sampling are restored by Model.
Custom Python callables and initializer implementations must remain available
with matching configuration. To save the full architecture and fitted state,
use esn.save("model.pt") and rd.load("model.pt"); see
save, load and diagrams.
The current ESN and Model metadata version is 2. Older metadata is rejected;
reconstruct and refit those models before saving a current checkpoint.
With the optional dynamics extra, fit(trajectory) and timestamped forecasts
work exactly as in the trajectory guide.
The named single-port spelling fit({"input": trajectory}) also works, with
explicit trajectory targets under {"output": target} when needed.
Ordinary calls always return Torch tensors; forecast(return_type="tensor")
keeps trajectory-trained predictions on the model device.
See the ESN migration guide for the breaking API changes.
Method reference¶
fit returns this same module. forecast produces autonomous predictions;
forward follows observed inputs with carried state. For differentiable
chunking, forward_stateless returns a prediction and named states without
changing the stored state. get_state, set_state and reset_state manage
streaming explicitly. Standard inherited Torch methods and checkpoint protocol
hooks remain available and are omitted from this reference.
facade
¶
A standard PyTorch ESN preset using the common resdag.Model workflow.
ESN
¶
ESN(
reservoir_size: int = 500,
*,
input_size: int | None = None,
spectral_radius: float = 0.9,
leak_rate: float = 1.0,
washout: int = 100,
alpha: float = 1e-06,
preprocessing: Preprocessing = "standard",
input_transforms: Mapping[str, Module] | None = None,
output_transforms: Mapping[str, Module] | None = None,
prediction_lead: int | Mapping[str, int] = 1,
feedback: Sequence[Feedback] | None = None,
readout: ReadoutSpec = "auto",
readout_kwargs: dict[str, Any] | None = None,
topology: TopologySpec = None,
feedback_initializer: InitializerSpec = None,
activation: str = "tanh",
bias: bool = True,
readout_bias: bool = True,
input_to_readout: bool = True,
trainable: bool = False,
seed: int | None = None,
device: device | str | None = None,
dtype: dtype | None = None,
resample_dt: float | None = None,
resample_method: Literal["linear", "pchip", "cubic"] = "linear",
**reservoir_kwargs: Any
)
Bases: Module
A classic ESN preset with the same original-unit workflow as Model.
ESN(input_size=3) builds eagerly, making all parameters available before
attaching an optimizer. Without input_size, fit infers the width
and attaches a successfully fitted workflow. Call build explicitly
when constructing a larger PyTorch pipeline before its first fit.
fit accepts floating Torch tensors or a TSDynamics trajectory. Ordinary
forward returns Torch tensors, carries recurrent state, preserves layout
and gradients, and uses fitted training-only scaling. forecast has the
same keyword-only horizon and return conventions as Model.
The single registered workflow child is a Model; its raw
symbolic graph is exposed by graph. Custom DAGs, drivers and multiple
outputs use Model directly. readout/readout_kwargs expose solver
choices; additional reservoir settings and custom initializers pass through
to resdag.models.classic_esn. input_to_readout=True includes the
raw input alongside reservoir states in the readout; False uses states
alone. Automatic tuning of this preset compares both choices by default.
An untouched lazy preset adopts the first floating tensor's device/dtype.
Explicit constructor placement or a pre-build to/double conversion
fixes placement; later fitting follows ordinary Torch placement validation.
build uses the current placement unless explicitly overridden. Checkpoints
record width and preset configuration, allowing a matching unbuilt preset to
load; arbitrary custom Python configurations must still be reconstructed.
Source code in src/resdag/facade.py
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 | |
input_size
property
¶
input_size: int | None
Observed feature width, available after eager construction/build/fit.
is_built
property
¶
is_built: bool
Whether the input width is fixed and the workflow has been constructed.
is_fitted
property
¶
is_fitted: bool
Whether readout fitting and training-only preprocessing succeeded.
graph
property
¶
graph: ESNModel
The original raw symbolic graph; call build() or fit() before access.
preprocessing
property
¶
preprocessing: str | None
Configured normalization method, or None when it is disabled.
prediction_leads
property
¶
Prediction offsets by output name; the preset has one 'output' head.
feedback
property
¶
Explicit feedback routes, or None for automatic output-to-input routing.
save_formats
property
¶
Supported complete-model checkpoint and diagram suffixes.
build
¶
Materialize parameters before attaching optimizers; same-width calls are idempotent.
Source code in src/resdag/facade.py
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 | |
fit
¶
fit(
training: Streams | Trajectory | Mapping[str, Trajectory],
targets: Streams | Trajectory | Mapping[str, Trajectory] | None = None,
) -> ESN
Fit with Model's train-only scaling, explicit targets and transactional refitting.
Source code in src/resdag/facade.py
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 | |
save
¶
Save this complete preset or a DAG diagram, selected by suffix.
Source code in src/resdag/facade.py
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 | |
plot_model
¶
Display or export the preset DAG without running it.
Source code in src/resdag/facade.py
457 458 459 | |
tune
¶
tune(
training: Streams | Trajectory | Mapping[str, Trajectory],
targets: Streams | Trajectory | Mapping[str, Trajectory] | None = None,
*,
preset: Literal["quick", "balanced", "thorough"] = "balanced",
n_trials: int | None = None,
horizon: int | None = None,
n_jobs: int = 1,
**options: Any
) -> ESN
Tune preset settings, refit the winner and return this same ESN.
Requires resdag[hpo]. Presets automatically rebuild reservoir
sizes, initializations and readouts together. search_space(trial)
overrides the default Optuna search. See the tuning guide for explicit
validation, seeds, objectives, study storage and tuning_report.
Failed tuning preserves the current model. Create optimizers afterward.
Source code in src/resdag/facade.py
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 | |
forward
¶
forward(inputs: Streams) -> Tensor
Predict original units with carried state and ordinary Torch autograd/hooks.
Source code in src/resdag/facade.py
497 498 499 | |
forward_stateless
¶
forward_stateless(
inputs: Streams,
*,
states: Mapping[str, Tensor] | None = None,
compile: bool = False
) -> tuple[Tensor, ReservoirStates]
Predict original-unit signals with explicitly returned recurrent state.
Inputs preserve the (time, features) or (batch, time, features)
layout used by forward. Omitting states starts from each
reservoir's configured reset state; otherwise provide the complete
mapping returned by an earlier call. The output and returned states
retain gradients across chunks. Stored recurrent state is unchanged.
Other modules retain their normal training-mode and hook behavior.
compile=True requests the existing supported compiled scan; its
device/capability checks and eager fallback follow Model.
Source code in src/resdag/facade.py
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 | |
forecast
¶
forecast(
history: Streams | Trajectory | Mapping[str, Trajectory] | None = None,
*,
horizon: int,
future_inputs: Streams | Trajectory | Mapping[str, Trajectory] | None = None,
return_warmup: bool = False,
compile: bool = False,
execution: Literal["fast", "history"] = "fast",
return_type: Literal["auto", "tensor", "trajectory"] = "auto"
) -> Tensor | Trajectory
Forecast horizon future samples in the original signal units.
history resynchronizes recurrence on an observed prefix; omit it
to use the fitted training tail. The first prediction follows its last
observed sample. Every call resets recurrence and temporarily disables
training noise. future_inputs supplies any declared non-feedback
drivers; the ordinary one-input preset needs none.
return_warmup=True prepends the readout's predictions during history
replay. execution='fast' uses framewise execution; 'history'
supports causal temporal transforms by replaying growing prefixes.
compile=True requests supported compiled forecasting. See
Model.forecast for capability checks and fallback behavior.
Tensor inputs retain their two- or three-dimensional layout.
return_type='auto' returns a TSDynamics trajectory after trajectory
fitting or with trajectory history; 'tensor' keeps Torch output on
the model device. A selected trajectory result requires a known clock.
Source code in src/resdag/facade.py
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 | |
reset_state
¶
reset_state() -> None
Clear carried recurrent state; the next call uses configured reset values.
Source code in src/resdag/facade.py
582 583 584 | |
get_state
¶
get_state() -> ReservoirStates
Return copies of initialized recurrent states, keyed as in forward_stateless.
Source code in src/resdag/facade.py
586 587 588 | |
set_state
¶
Restore named recurrent states using Model.set_state validation.
strict=True requires the model's complete state-key set. Restored
states are copied and matched to each reservoir's device and dtype.
Source code in src/resdag/facade.py
590 591 592 593 594 595 596 | |