Reference
Core¶
Model adds named inputs/outputs, fitted scaling and fit/forecast operations
around a functional graph. Start with the
common model guide. ESNModel remains the
underlying symbolic graph with lower-level training and state interfaces.
For timestamped runs, see TSDynamics trajectories.
Several ports use named trajectories;
per-port unit conversions use custom preprocessing.
Use Feedback(output="prediction", input="state", delay=1) to declare a
named recurrent connection. Prediction leads and feedback delays have separate
meanings; see feedback and clocks.
forward_stateless returns predictions and a ReservoirStates mapping without
changing stored recurrent state. Reuse the returned mapping for differentiable
chunks. Raw graph as_module() returns a ReservoirModelModule that shares
the complete graph and its parameters; ReservoirFeatureExtractor selects
reservoir features instead. These adapters serve different pipeline needs.
Standard inherited PyTorch operations, including parameters, state_dict,
load_state_dict, train, eval and to, remain available. Their inherited
reference entries and checkpoint protocol hooks are omitted here.
core
¶
Core Model¶
This module provides the main model class and input helpers for building
ESN architectures using the pytorch_symbolic library.
| CLASS | DESCRIPTION |
|---|---|
Model |
Named functional graph with training-only scaling and a PyTorch lifecycle. |
ESNModel |
Extended SymbolicModel with ESN-specific methods for forecasting and reservoir state management. |
ReservoirFeatureExtractor |
|
Input |
Alias for |
| FUNCTION | DESCRIPTION |
|---|---|
reservoir_input |
Convenience constructor for a per-feature symbolic input tensor with
a placeholder time dimension. Preferred over hand-crafting
|
Examples:
Building a simple ESN:
>>> from resdag.core import ESNModel, reservoir_input
>>> from resdag.layers import ESNLayer
>>> from resdag.layers.readouts import CGReadoutLayer
>>>
>>> inp = reservoir_input(3) # equivalent to ps.Input((1, 3))
>>> reservoir = ESNLayer(200, feedback_size=3)(inp)
>>> readout = CGReadoutLayer(200, 3)(reservoir)
>>> model = ESNModel(inp, readout)
Multi-input model:
>>> feedback = reservoir_input(3)
>>> driver = reservoir_input(5)
>>> reservoir = ESNLayer(200, feedback_size=3, input_size=5)(feedback, driver)
>>> readout = CGReadoutLayer(200, 3)(reservoir)
>>> model = ESNModel([feedback, driver], readout)
See Also
resdag.models : Premade ESN architectures. resdag.training.ESNTrainer : Trainer for fitting readouts.
Model
¶
Model(
*,
inputs: Mapping[str, SymbolicData] | None = None,
outputs: Mapping[str, SymbolicData] | None = None,
graph: Module | None = None,
input_names: Sequence[str] | None = None,
output_names: Sequence[str] | None = None,
washout: int = 100,
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,
resample_dt: float | None = None,
resample_method: Literal["linear", "pchip", "cubic"] = "linear"
)
Bases: Module
Wrap a named functional DAG in a common training/prediction workflow.
Supply inputs={name: symbolic_input} and outputs={name: symbolic_output},
or graph=existing_model with optional ordered input_names and
output_names. The graph is registered once as graph; it remains
available for raw, already-normalized tensor execution. Existing symbolic,
parallel local-state and coupled ensemble backends are supported. Parallel
ports describe the full field; coupled members share one aggregate output.
Coupled fitting trains member readouts only. A custom feed-forward aggregator
is supplied/configured by the user and can be optimized separately with
ordinary PyTorch. Reservoirs hidden inside an aggregator require ordinary
stateful forward rather than explicit-state execution or forecasting.
fit(series) learns future prediction for one input/output of equal
width. fit(inputs, targets={output_name: tensor}) instead fits explicit,
time-aligned targets; all streams include the same washout prefix. Declared intermediate heads may feed
later reservoirs; readout_targets supervises internal fitted heads
without adding them to public outputs.
forward accepts floating Torch tensors, preserves 2-D/3-D layout and
gradients, applies fitted scaling and returns original units. Calls carry
recurrent state by default; call reset_state between unrelated
sequences. One head returns a Tensor; several return a named dictionary.
Preprocessing is "standard" by default, any existing normalization
method, or "off"/None. Statistics use training inputs/targets after
washout only. Implicit targets share their input's statistics. Feedback
automatically converts each output back to original units before applying
its destination input's scaling.
prediction_lead declares the physical target distance for each head:
input at step t predicts target at t + lead. The default is one;
a mapping overrides named heads. feedback supplies explicit
Feedback connections with independent graph-step delays. Without
connections, the first output automatically feeds the first input after
its prediction lead. An empty sequence leaves all inputs externally driven.
state_dict includes scaling, ordered port metadata and the observed tail;
reconstruct the same DAG before loading. tune compares candidates and
installs a refitted winner; its report exposes the Optuna study. Complete
save("run.pt") and rd.load preserve the complete model; diagram
suffixes export its declared structure without running it.
With the optional dynamics extra, bare or named TSDynamics trajectories
use one shared observed clock. Explicit targets are aligned to each head's
physical prediction lead. Forecasts return one trajectory or a named
dictionary, with target component names and shared future times.
return_type="tensor" keeps predictions on the model device.
Ordinary forward always uses Torch tensors.
Uneven timestamps are automatically interpolated with resample_method
(linear, PCHIP or cubic); resample_dt controls the physical step.
Source code in src/resdag/core/workflow.py
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 297 | |
preprocessing
property
¶
preprocessing: NormMethod | None
The fallback policy; explicit transform overrides apply independently.
is_fitted
property
¶
is_fitted: bool
Whether this workflow has completed fitting or restored a fitted checkpoint.
prediction_leads
property
¶
Physical target distances by public output name.
feedback
property
¶
Explicit connections, or None for the automatic first-port route.
internal_readout_names
property
¶
Target keys for internal fitted heads, without exposing extra predictions.
save_formats
property
¶
Supported complete-model checkpoint and diagram suffixes.
forward
¶
forward(inputs: Streams) -> WorkflowOutput
Predict in original units, retaining gradients and carried recurrent state.
Source code in src/resdag/core/workflow.py
494 495 496 497 498 | |
forward_stateless
¶
forward_stateless(
inputs: Streams,
*,
states: Mapping[str, Tensor] | None = None,
compile: bool = False
) -> tuple[WorkflowOutput, ReservoirStates]
Predict original units with caller-managed recurrent states and gradients.
Source code in src/resdag/core/workflow.py
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 | |
reset_state
¶
reset_state() -> None
Start the next ordinary forward from the reservoirs' configured reset states.
Source code in src/resdag/core/workflow.py
525 526 527 | |
get_state
¶
get_state() -> ReservoirStates
Copy reservoir states, excluding a forecast's ephemeral feedback queues.
Forecast calls replay history and construct fresh delay queues. These tensors alone do not resume a delayed forecast at its previous clock.
Source code in src/resdag/core/workflow.py
529 530 531 532 533 534 535 | |
set_state
¶
Restore ordinary-forward reservoir states, not delayed-rollout queues.
Source code in src/resdag/core/workflow.py
537 538 539 | |
plot_model
¶
plot_model(
*,
save_path: str | Path | None = None,
format: str | None = None,
show_shapes: bool = True,
show_trainable: bool = False,
rankdir: str = "LR"
) -> Any
Display a DAG in notebooks or export SVG/PNG/PDF/DOT without running it.
Source code in src/resdag/core/workflow.py
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 | |
save
¶
save(
path: str | Path,
*,
format: str | None = None,
include_state: bool = True,
trusted: bool = False,
metadata: Mapping[str, Any] | None = None,
**diagram_options: Any
) -> Any
Save a complete loadable model (.pt/.pth) or a diagram by suffix.
rd.load(path) reconstructs checkpoints without a prebuilt DAG.
Current ordinary-forward memory is included by default. Set
trusted=True only to bundle notebook-defined Python code; loading
such a bundle also requires explicit trust. Diagram formats are
SVG/PNG/PDF/DOT and accept plot_model options.
Source code in src/resdag/core/workflow.py
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 | |
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
) -> Model
Tune autonomous forecasts, refit the winner and return this model.
Requires resdag[hpo]. The final 20% is held out while comparing
candidates, then the winner is refitted on all supplied data. Keep a
separate final test set. Built-in classic/OTT graphs have an automatic
rebuilding recipe. factory(params, seed) rebuilds custom DAGs;
without one, custom sizes and weights stay fixed and alpha/washout can vary.
search_space(trial) uses ordinary Optuna suggestions. Advanced
options and tuning_report are documented in the tuning guide.
A failure leaves this model unchanged. Tune before creating optimizers.
Source code in src/resdag/core/workflow.py
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 | |
fit
¶
fit(
training: Streams | Trajectory | Mapping[str, Trajectory],
targets: Streams | Trajectory | Mapping[str, Trajectory] | None = None,
*,
readout_targets: Mapping[str, Tensor] | None = None
) -> Model
Fit public and internal heads transactionally and retain the original observed tail.
Implicit supervision pairs input t with observation
t + prediction_lead and retains the complete observed tail.
Explicit targets are already caller-aligned to input indices; declared
leads describe their physical timestamps without shifting those arrays.
Successful fitting resets streaming state. Failed fitting leaves the
existing graph, fitted preprocessing and cached history unchanged.
Bare or named TSDynamics trajectories share one physical input grid.
Explicit trajectory targets are sampled at origin + prediction_lead*dt;
tensors remain caller-aligned. Regression uses jointly supported origins
after absolute washout. Target source observations after the common input
endpoint are held out before interpolation. The cached tail includes the
final observed inputs, even after the last supervised origin. Tensor
refitting clears trajectory defaults on success.
readout_targets={"stage1": tensor} supervises internal readouts
without exposing them as outputs. Keys use the readout's name or
graph path; coupled members use models.<index>.<name>. Tensors share
the complete input time axis, including washout, and express the desired
internal output units without automatic output scaling. For trajectory
inputs, align these tensors to the prepared shared input grid.
Source code in src/resdag/core/workflow.py
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 | |
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"
) -> WorkflowOutput | Trajectory | dict[str, Trajectory]
Return named heads aligned to the immediate unseen physical sample.
future_inputs names every input without a feedback connection.
Drivers start immediately after history and require
max(0, horizon - min(prediction_leads)) samples. With the default
next-step head this is horizon - 1. History must contain at least
the largest prediction lead and feedback delay. Warmup predictions
already provide the first unseen samples; they are never skipped.
return_warmup prepends predictions on the shared physical timeline
starting at history index max(prediction_leads).
Every call rebuilds pending feedback from history and temporarily
disables training noise. execution='fast' requires pointwise graph
modules or explicit reservoir adapters. 'history' replays the full
growing input prefix for pure causal sequence modules, at higher cost.
Custom modules may declare supports_framewise=True when appropriate.
Compiled forecasting is currently available for symbolic graphs only;
parallel and coupled backends require compile=False.
return_type="auto" returns a TSDynamics trajectory after trajectory
fitting or with trajectory history; otherwise it returns tensors.
"tensor" avoids conversion to NumPy/CPU. A selected trajectory result
needs timestamped history or the cached training context; a new tensor
history has no absolute clock. Trajectory history is resampled to the
fitted physical step and must retain fitted component names/order.
Source code in src/resdag/core/workflow.py
960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 | |
Feedback
dataclass
¶
Connect a named output to a named input after delay graph steps.
An output produced at graph step q is consumed at step q + delay.
This delay is independent of the output's prediction_lead: a head with
lead two estimates the physical sample two steps after its input. Matching
lead and delay gives naturally aligned self-feedback; other combinations
deliberately model lagged coupling. Widths must match at both ports.
ESNModel
¶
Bases: SymbolicModel
Echo State Network model with forecasting and state management.
This class extends pytorch_symbolic.SymbolicModel with ESN-specific
functionality including:
- Time series forecasting with warmup and autoregressive generation
- Reservoir state management (reset, get, set)
- Model persistence (save/load)
- Architecture visualization
The model inherits all standard torch.nn.Module functionality and
the summary() method from pytorch_symbolic.
Pass symbolic inputs and outputs to the constructor (see
pytorch_symbolic.SymbolicModel).
| ATTRIBUTE | DESCRIPTION |
|---|---|
inputs |
List of model input tensors.
TYPE:
|
outputs |
List of model output tensors.
TYPE:
|
output_shape |
Shape(s) of model outputs.
TYPE:
|
Examples:
Create and use a simple ESN:
>>> import pytorch_symbolic as ps
>>> from resdag.core import ESNModel
>>> from resdag.layers import ESNLayer
>>> from resdag.layers.readouts import CGReadoutLayer
>>>
>>> inp = ps.Input((100, 3))
>>> reservoir = ESNLayer(200, feedback_size=3)(inp)
>>> readout = CGReadoutLayer(200, 3)(reservoir)
>>> model = ESNModel(inp, readout)
>>>
>>> # Forward pass
>>> x = torch.randn(4, 100, 3)
>>> y = model(x)
>>> print(y.shape)
torch.Size([4, 100, 3])
Forecasting with warmup:
>>> warmup_data = torch.randn(1, 50, 3)
>>> predictions = model.forecast(warmup_data, horizon=100)
>>> print(predictions.shape)
torch.Size([1, 100, 3])
See Also
pytorch_symbolic.SymbolicModel : Parent class. BaseReservoirLayer : Reservoir layer component. ESNTrainer : Trainer for fitting readout layers.
pytorch_symbolic.SymbolicModel propagates shapes by running each
layer's real forward on a torch.rand placeholder (batch size 1).
For a stateful resdag.layers.reservoirs.base_reservoir.BaseReservoirLayer
that leaves the layer holding a saturated trace state at batch=1.
A fresh model used directly at batch=1 (e.g. y = model(x) or
standard forecasting) would silently continue from this junk instead of a
clean zero state — batch sizes != 1 auto-resize to zeros and escape
it, but batch=1 direct calls do not. Resetting here, once, right after
the graph is built, makes every freshly constructed model start from a
clean state regardless of how it is first called.
Source code in src/resdag/core/model.py
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 | |
forward_stateless
¶
forward_stateless(
*inputs: Tensor, states: Mapping[str, Tensor] | None = None, compile: bool = False
) -> tuple[ModelOutput, ReservoirStates]
Run the complete DAG with explicit recurrent states.
Inputs use (batch, time, features). Omitting states starts each
reservoir from its configured reset state (zero by default). Otherwise
pass the complete state dictionary returned by an earlier call; keys
match get_reservoir_states.
The returned output includes every original transform and readout.
Stored reservoir states and supplied state tensors are not changed.
Returned states retain gradients across chunks. Detach their tensors explicitly when truncated backpropagation is desired. Ordinary layer behavior (such as BatchNorm running statistics in training mode) still applies to non-reservoir modules in the graph.
Each graph position must use a distinct reservoir layer instance. Separate instances may share weights, but sharing their recurrent state would make predictions depend on sequence chunk boundaries.
Source code in src/resdag/core/model.py
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 | |
as_module
¶
as_module(*, stateful: bool = False) -> 'ReservoirModelModule'
Wrap the complete trained graph for a larger PyTorch pipeline.
The wrapper shares this model's parameters and readouts. The default
processes independent batches without touching stored reservoir state.
Set stateful=True to carry state between calls, as model(x)
does, or use the wrapper's forward_stateless for explicit state.
Source code in src/resdag/core/model.py
372 373 374 375 376 377 378 379 380 381 382 383 384 | |
reset_reservoirs
¶
reset_reservoirs() -> None
Reset all reservoir layers for lazy initialization from their configured state.
This clears the internal hidden states of all BaseReservoirLayer
modules in the model, preparing it for a new sequence.
Examples:
>>> model.reset_reservoirs()
>>> output = model(new_sequence)
Source code in src/resdag/core/model.py
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 | |
set_random_reservoir_states
¶
set_random_reservoir_states(
batch_size: int | None = None,
device: device | None = None,
dtype: dtype | None = None,
) -> None
Set random states of all reservoir layers.
| PARAMETER | DESCRIPTION |
|---|---|
batch_size
|
If provided, lazily initialise each reservoir's state with this batch size before filling it with random values.
TYPE:
|
device
|
Target device for lazy initialisation.
TYPE:
|
dtype
|
Target dtype for lazy initialisation.
TYPE:
|
Examples:
>>> model.set_random_reservoir_states() # state must exist
>>> model.set_random_reservoir_states(batch_size=4) # lazy
Source code in src/resdag/core/model.py
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 | |
get_reservoir_states
¶
Get current states of all reservoir layers.
| RETURNS | DESCRIPTION |
|---|---|
dict of str to torch.Tensor
|
Dictionary mapping layer names to their state tensors. Only includes reservoirs with non-None states. |
Examples:
>>> states = model.get_reservoir_states()
>>> for name, state in states.items():
... print(f"{name}: {state.shape}")
Source code in src/resdag/core/model.py
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 | |
get_state
¶
get_state() -> ReservoirStates
Return named copies of all currently initialized recurrent states.
Source code in src/resdag/core/model.py
452 453 454 | |
set_state
¶
Restore named recurrent states; names match forward_stateless.
Source code in src/resdag/core/model.py
456 457 458 | |
set_reservoir_states
¶
Set states of reservoir layers.
| PARAMETER | DESCRIPTION |
|---|---|
states
|
Dictionary mapping layer names to state tensors.
Names should match those returned by
TYPE:
|
strict
|
If
TYPE:
|
Notes
Each restored tensor is routed through
resdag.layers.reservoirs.base_reservoir.BaseReservoirLayer.set_state,
which clones the tensor and validates its shape against the target
cell's contract (e.g. the 2-D (batch, reservoir_size) layout of an
ESN). Before validation the tensor is coerced to the target
reservoir's reference device and dtype (its first floating-point
parameter/buffer) so that a state saved on one device/dtype is not
silently re-zeroed by _maybe_init_state on the next forward pass —
the canonical save-on-GPU / load-on-CPU round-trip therefore preserves
the warmed-up state values.
| RAISES | DESCRIPTION |
|---|---|
KeyError
|
If |
ValueError
|
If a restored tensor does not match the target cell's state-shape contract. The error names the cell class and the offending shape. |
| WARNS | DESCRIPTION |
|---|---|
UserWarning
|
If a restored state had to be moved to a different device or cast to a different dtype to match its target reservoir. |
Examples:
>>> states = model.get_reservoir_states()
>>> # ... do something ...
>>> model.set_reservoir_states(states) # Restore states
Source code in src/resdag/core/model.py
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 | |
save
¶
Save model weights and optionally reservoir states.
| PARAMETER | DESCRIPTION |
|---|---|
path
|
File path to save the model. Parent directories are created if they don't exist. |
include_states
|
If True, also save current reservoir states. Only reservoirs whose
state is non-
TYPE:
|
**metadata
|
Additional metadata to store with the model (e.g., training info).
TYPE:
|
Examples:
Save model weights only:
>>> model.save("model.pt")
Save with states and metadata:
>>> model.save(
... "checkpoint.pt",
... include_states=True,
... epoch=10,
... loss=0.05
... )
See Also
load : Load model from file.
Source code in src/resdag/core/model.py
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 | |
load
¶
load(
path: str | Path,
strict: bool = True,
load_states: bool = False,
map_location: Any = None,
) -> None
Load model weights from file.
| PARAMETER | DESCRIPTION |
|---|---|
path
|
File path to load from. |
strict
|
If True, strictly enforce that state_dict keys match.
TYPE:
|
load_states
|
If True, also load reservoir states if available. States are
restored tolerantly (
TYPE:
|
map_location
|
Passed to
TYPE:
|
| WARNS | DESCRIPTION |
|---|---|
UserWarning
|
If |
Examples:
>>> model.load("model.pt")
>>> model.load("checkpoint.pt", load_states=True)
See Also
save : Save model to file. load_from_file : Class method for loading.
Source code in src/resdag/core/model.py
595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 | |
load_from_file
classmethod
¶
load_from_file(
path: str | Path,
model: "ESNModel | None" = None,
strict: bool = True,
load_states: bool = False,
map_location: Any = None,
) -> "ESNModel"
Load weights into an existing model instance.
This is a convenience class method that loads state dict into a pre-constructed model.
| PARAMETER | DESCRIPTION |
|---|---|
path
|
File path to load from. |
model
|
Model instance to load weights into. Required.
TYPE:
|
strict
|
If True, strictly enforce state_dict key matching.
TYPE:
|
load_states
|
If True, also load reservoir states.
TYPE:
|
map_location
|
Storage-device remapping forwarded to
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ESNModel
|
The model instance with loaded weights. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Examples:
>>> model = create_my_model() # Create architecture
>>> model = ESNModel.load_from_file("weights.pt", model=model)
Source code in src/resdag/core/model.py
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 | |
save_full
¶
Serialize the entire model — architecture, weights, and reservoir states — to a single file.
Unlike save, which stores only the state_dict (so the
architecture must be re-created before load), this pickles the
whole model object, the pytorch_symbolic graph included. Restore it
with load_full without rebuilding anything. This relies on the
pickle support added in pytorch-symbolic 1.2.
| PARAMETER | DESCRIPTION |
|---|---|
path
|
File path to save to. Parent directories are created if needed. |
**metadata
|
Additional metadata stored alongside the model (e.g. training info).
TYPE:
|
Notes
The file is a regular torch.save payload, loaded back with
weights_only=False — only open files you trust. Current reservoir
states are captured as-is; reset or warm up beforehand to control what
is persisted.
Any custom callable passed as a topology, *_initializer, or
activation spec must be importable (a module-level def, not a
lambda or locally-defined function) for the model to pickle. Specs
given as strings, (name, kwargs) tuples, or registered objects
always serialize. If a callable is not picklable, use the lighter
state-dict save instead.
Examples:
>>> model.save_full("model_full.pt", epoch=10)
>>> restored = ESNModel.load_full("model_full.pt", trusted=True) # trusted file
>>> predictions = restored.forecast(warmup, horizon=100)
See Also
load_full : Reconstruct a model saved with this method. save : Lighter, state-dict-only persistence (architecture not stored).
Source code in src/resdag/core/model.py
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 | |
load_full
classmethod
¶
load_full(
path: str | Path,
return_metadata: bool = False,
map_location: Any = None,
*,
trusted: bool = False
) -> "ESNModel | tuple[ESNModel, dict[str, Any]]"
Reconstruct a complete model saved with save_full.
No pre-built architecture is required — the model object, its symbolic
graph, weights, and reservoir states are all restored from the file.
This executes saved Python and requires explicit trusted=True.
| PARAMETER | DESCRIPTION |
|---|---|
path
|
File path written by |
return_metadata
|
If True, return
TYPE:
|
map_location
|
Passed to
TYPE:
|
trusted
|
Required explicit opt-in to unpickle executable Python. Prefer
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ESNModel or tuple of (ESNModel, dict)
|
The reconstructed model, optionally paired with its metadata dict. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the file does not contain a whole model — e.g. it is a
state-dict checkpoint from |
Warnings
Loads with weights_only=False, which unpickles arbitrary Python
objects. Only call this on files from a source you trust.
Notes
Accepts both save_full files (a metadata wrapper) and bare
torch.save(model) files (the model object on its own); the latter
carry no metadata.
Examples:
>>> model.save_full("model_full.pt")
>>> restored = ESNModel.load_full("model_full.pt", trusted=True)
>>> model_cpu = ESNModel.load_full("gpu_model.pt", map_location="cpu", trusted=True)
See Also
save_full : Serialize a complete model. load_from_file : Load a state-dict checkpoint into an existing model.
Source code in src/resdag/core/model.py
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 | |
plot_model
¶
plot_model(
show_shapes: bool = False,
show_trainable: bool = False,
rankdir: str = "TB",
save_path: str | Path | None = None,
format: str | None = None,
**kwargs: Any
) -> Any
Return a Graphviz source or export SVG/PNG/PDF/DOT, inferred by suffix.
Graph inspection does not execute layers or open a system viewer.
SVG/PNG/PDF require resdag[viz] and the Graphviz executable;
DOT works without either optional dependency.
Source code in src/resdag/core/model.py
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 | |
warmup
¶
warmup(
*inputs: Tensor,
return_outputs: bool = False,
reset: bool = True,
no_grad: bool = True
) -> Tensor | tuple[Tensor, ...] | None
Teacher-forced warmup to synchronize reservoir states.
Runs the model forward with provided inputs, updating internal reservoir states to achieve the Echo State Property (synchronization with input dynamics).
| PARAMETER | DESCRIPTION |
|---|---|
*inputs
|
Input tensors of shape
TYPE:
|
return_outputs
|
If True, return model outputs during warmup.
TYPE:
|
reset
|
If True, reservoir states are reset to
TYPE:
|
no_grad
|
If True (default), the warmup pass runs under For gradients to flow across the warmup→forecast boundary the
reservoir must also keep its carried state attached: set
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
torch.Tensor or tuple of torch.Tensor or None
|
If |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If no inputs are provided. |
Examples:
Synchronize states without capturing output:
>>> model.warmup(feedback_data)
Synchronize and capture output:
>>> outputs = model.warmup(feedback_data, return_outputs=True)
With driving input:
>>> model.warmup(feedback, driving_signal)
Continue warming from a saved state:
>>> model.set_reservoir_states(saved_states)
>>> model.warmup(more_data, reset=False)
See Also
forecast : Two-phase forecasting with warmup and generation. reset_reservoirs : Reset all reservoir states.
Source code in src/resdag/core/model.py
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 | |
forecast
¶
forecast(
warmup_inputs: tuple[Tensor, ...] | Tensor,
forecast_inputs: tuple[Tensor, ...] | Tensor | None = None,
*,
horizon: int,
initial_feedback: Tensor | None = None,
return_warmup: bool = False,
reset: bool = True,
compile: bool = False,
no_grad: bool = True,
alignment: ForecastAlignment = "next"
) -> Tensor | tuple[Tensor, ...]
Predict the next horizon samples after an observed history.
Training pairs input x[t] with target x[t+1]. Accordingly, the
final teacher-forced warmup output is already the prediction of the
first unseen sample. It becomes forecast slot zero; the remaining
horizon - 1 slots feed predictions back into the model.
| PARAMETER | DESCRIPTION |
|---|---|
warmup_inputs
|
Observed history, shaped
TYPE:
|
forecast_inputs
|
Future drivers beginning immediately after the warmup drivers.
Driver
TYPE:
|
horizon
|
Number of predictions, a positive integer. Zero is rejected; use a normal forward/warmup call when no future predictions are needed.
TYPE:
|
initial_feedback
|
A distinct additional observed input of shape
TYPE:
|
return_warmup
|
Prepend historical predictions. With default alignment, the last
warmup prediction is already forecast slot zero, so the full result
has
TYPE:
|
reset
|
Reset reservoir states before warmup. False continues current states.
TYPE:
|
compile
|
Compile the flat autoregressive executor when supported, falling
back to eager execution with a warning if compilation fails.
Incompatible with
TYPE:
|
no_grad
|
Disable autograd for inference. False makes the warmup and rollout
differentiable. For gradients through carried warmup state, set
each reservoir's
TYPE:
|
alignment
|
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
torch.Tensor or tuple of torch.Tensor
|
|
Notes
Returned predictions have not yet been consumed as inputs. After a
forecast, the stored state has consumed the history and all predictions
except the final one. To continue without replaying history, pass empty
warmup streams, initial_feedback=prediction[:, -1:] and reset=False
(plus the corresponding future drivers).
Hook-free autoregressive steps use a cached flat execution plan. When
PyTorch execution hooks are registered, native module calls preserve
their behavior during warmup and generated steps. Hooks added or removed
after an earlier forecast take effect automatically. Registered hooks
select eager compatible execution when compile=True is requested.
Custom non-reservoir operations must declare supports_framewise=True.
Whole-sequence custom operations can use the common Model wrapper's
forecast(execution="history") instead.
Examples:
>>> predictions = model.forecast(observed, horizon=100)
>>> # predictions[:, 0] estimates the sample immediately after observed.
Source code in src/resdag/core/model.py
943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 | |
windowed_forecast
¶
windowed_forecast(
series: Tensor,
*driver_series: Tensor,
predict_len: int,
teacher_len: int,
warmup_len: int | None = None,
reset: bool = True,
return_mask: bool = False,
no_grad: bool = True
) -> Tensor | tuple[Tensor, Tensor]
Gap-filling reconstruction by alternating re-sync and free-running.
Reconstruct a long trajectory that is only observed in periodic
windows: the reservoir is repeatedly re-synchronized on a short window
of real data (teacher forcing) and then left to forecast autonomously
across the unobserved gap. Because the Echo State Property gives the
reservoir fading memory, every teacher-forced window pulls its state
back onto the true trajectory, no matter how far the previous free run
had drifted — so per-window error does not compound across windows
(accuracy within a gap still depends on keeping predict_len short
relative to the system's predictability horizon).
The reservoir state is carried across the whole pass (it is reset only
once, at the start, and only when reset=True). Each cycle is one
forecast call: its warmup phase is the re-sync window and its
autoregressive phase is the gap.
Timeline (W = warmup_len, F = teacher_len, P = predict_len):
[== warmup W ==][~~ gap P ~~][= teacher F =][~~ gap P ~~][= F =]...
observed filled observed filled obs
(teacher-forced) (forecast) (teacher-forced) (forecast)
Observed segments are copied verbatim from series; gap segments are
replaced by the model's autonomous forecast. Any trailing steps that
cannot host a full re-sync window plus at least one forecast step are
left as observed.
| PARAMETER | DESCRIPTION |
|---|---|
series
|
Ground-truth feedback series of shape
TYPE:
|
*driver_series
|
Exogenous driver series, one per driver input of the model, each of
shape
TYPE:
|
predict_len
|
Length |
teacher_len
|
Length |
warmup_len
|
Length
TYPE:
|
reset
|
If True, reservoir states are reset before the first window. Set False to continue from the current (already warmed) state.
TYPE:
|
return_mask
|
If True, also return a 1-D boolean mask of length
TYPE:
|
no_grad
|
If True (default), every cycle runs under
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
reconstruction
|
Reconstructed series of shape
TYPE:
|
mask
|
Only if
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Notes
- The forecast steps to score are exactly
reconstruction[:, ~mask]againstseries[:, ~mask]— the values the model had to infer without ever seeing them. - For multi-output models the first output is fed back (as in
forecast) and only that channel is reconstructed.
Examples:
Reconstruct a Lorenz trajectory observed 40 steps out of every 240, filling 200-step gaps:
>>> recon, mask = model.windowed_forecast(
... series, # (1, T, 3) ground truth
... predict_len=200,
... teacher_len=40,
... return_mask=True,
... )
>>> gap_rmse = ((recon[:, ~mask] - series[:, ~mask]) ** 2).mean().sqrt()
With an exogenous driver:
>>> recon = model.windowed_forecast(
... feedback_series, driver_series,
... predict_len=100, teacher_len=50,
... )
See Also
forecast : A single warmup + autoregressive forecast cycle. warmup : Teacher-forced state synchronization only.
Source code in src/resdag/core/model.py
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 | |
ReservoirModelModule
¶
Bases: Module
A standard module preserving a trained model's full DAG and parameters.
Construct with model.as_module(). The source model is registered as a
child module, so parameters(), state_dict(), train()/eval() and
to(device, dtype) behave like ordinary PyTorch composition. Parameters
are shared with the source, not copied.
Source code in src/resdag/core/model.py
1363 1364 1365 1366 1367 1368 1369 1370 1371 | |
forward
¶
forward(*inputs: Tensor) -> ModelOutput
Predict independent sequences from each reservoir's configured reset state.
Source code in src/resdag/core/model.py
1377 1378 1379 1380 1381 1382 1383 | |
forward_stateless
¶
forward_stateless(
*inputs: Tensor, states: Mapping[str, Tensor] | None = None, compile: bool = False
) -> tuple[ModelOutput, ReservoirStates]
Predict with explicitly supplied and returned reservoir states.
Source code in src/resdag/core/model.py
1385 1386 1387 1388 1389 1390 1391 1392 | |
reset_state
¶
reset_state() -> None
Reset the source model's stored states for stateful streaming.
Source code in src/resdag/core/model.py
1394 1395 1396 | |
get_state
¶
get_state() -> ReservoirStates
Return copies of the wrapped model's initialized streaming states.
Source code in src/resdag/core/model.py
1398 1399 1400 | |
set_state
¶
Restore the wrapped model's streaming states.
Source code in src/resdag/core/model.py
1402 1403 1404 | |
ReservoirFeatureExtractor
¶
ReservoirFeatureExtractor(
reservoir_size: int | Iterable[int] | None = None,
feedback_size: int | None = None,
input_size: int | None = None,
trainable: bool = False,
layers: BaseReservoirLayer | Iterable[BaseReservoirLayer] | None = None,
stateful: bool = True,
**layer_kwargs: object
)
Bases: Module
nn.Sequential-friendly reservoir feature extractor.
Wraps one reservoir layer (or a stack of them) as a plain
torch.nn.Module that maps a feedback sequence
(batch, timesteps, feedback_size) (plus an optional driving input) to
reservoir features (batch, timesteps, reservoir_size). Because the
feedback-only case takes a single positional input, the extractor drops
straight into a torch.nn.Sequential ahead of any trainable head:
model = nn.Sequential(
ReservoirFeatureExtractor(reservoir_size=300, feedback_size=3),
nn.Linear(300, 3),
)
The reservoir is frozen by default (its parameters do not require
gradients), so a single optimizer over model.parameters() trains only
the head — the canonical reservoir-computing setup. Pass trainable=True
(or call unfreeze) to backpropagate through the recurrence as well.
Stacking is supported: passing several feedback dimensions, or constructing the extractor from pre-built layers, chains the reservoirs so each consumes the previous reservoir's features as its feedback signal. A driving input, when supplied, is passed to the first reservoir only.
| PARAMETER | DESCRIPTION |
|---|---|
reservoir_size
|
Reservoir width. An
TYPE:
|
feedback_size
|
Dimension of the feedback signal entering the first reservoir.
Required unless
TYPE:
|
input_size
|
Dimension of an optional driving input fed to the first reservoir. If
TYPE:
|
trainable
|
If
TYPE:
|
layers
|
Pre-built reservoir layer(s) to wrap directly instead of constructing
new ones. Any
TYPE:
|
stateful
|
Carry reservoir states between forward calls. Use
TYPE:
|
**layer_kwargs
|
Extra keyword arguments forwarded to every
TYPE:
|
| ATTRIBUTE | DESCRIPTION |
|---|---|
reservoirs |
The wrapped reservoir layer(s), in feed order.
TYPE:
|
output_size |
Feature dimension of the extractor's output (the last reservoir's
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If neither |
Examples:
Drop straight into a torch.nn.Sequential and train the head with a
single optimizer:
>>> import torch
>>> import torch.nn as nn
>>> from resdag import ReservoirFeatureExtractor
>>> model = nn.Sequential(
... ReservoirFeatureExtractor(reservoir_size=64, feedback_size=3),
... nn.Linear(64, 3),
... )
>>> x = torch.randn(2, 50, 3) # (batch, time, features)
>>> y = model(x)
>>> y.shape
torch.Size([2, 50, 3])
The reservoir is frozen by default, so only the head receives gradients:
>>> extractor = model[0]
>>> all(not p.requires_grad for p in extractor.parameters())
True
Re-zero the stateful reservoir between epochs:
>>> for epoch in range(3):
... extractor.on_epoch_start() # alias of reset_state()
... # ... train one epoch ...
Reuse the reservoir of an existing resdag.core.ESNModel (shared,
not copied):
>>> from resdag import ESNModel, ESNLayer, reservoir_input
>>> inp = reservoir_input(3)
>>> states = ESNLayer(64, feedback_size=3)(inp)
>>> esn = ESNModel(inp, states)
>>> extractor = ReservoirFeatureExtractor.from_model(esn)
See Also
resdag.layers.reservoirs.ESNLayer : The reservoir layer being wrapped. resdag.core.ESNModel : Build an extractor from an existing model.
Source code in src/resdag/core/feature_extractor.py
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 | |
is_frozen
property
¶
is_frozen: bool
bool: True when no wrapped reservoir parameter requires gradients.
output_size
property
¶
output_size: int
int: Feature dimension of the extractor output (last reservoir width).
from_model
classmethod
¶
from_model(
esn_model: Module, trainable: bool = False, stateful: bool = True
) -> ReservoirFeatureExtractor
Build an extractor that reuses the reservoir layers of an existing model.
The reservoir layers of esn_model are wrapped by reference — the
returned extractor shares their parameters (and stateful buffers) with
the source model, it does not copy them. Training (or freezing) one
therefore affects the other.
| PARAMETER | DESCRIPTION |
|---|---|
esn_model
|
A model containing one or more
TYPE:
|
trainable
|
Freeze/unfreeze toggle applied to the shared reservoir layers after
wrapping. Because the layers are shared, this also changes
TYPE:
|
stateful
|
Carry state between calls.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ReservoirFeatureExtractor
|
Extractor wrapping the model's reservoir layers by reference. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Notes
This extracts and chains reservoir layers only; it does not reproduce arbitrary parallel branches, intermediate transforms, or the trained readout. Embed the source model itself to preserve its full graph.
Examples:
>>> from resdag import ESNModel, ESNLayer, reservoir_input
>>> from resdag import ReservoirFeatureExtractor
>>> inp = reservoir_input(3)
>>> states = ESNLayer(64, feedback_size=3)(inp)
>>> esn = ESNModel(inp, states)
>>> extractor = ReservoirFeatureExtractor.from_model(esn)
>>> src = next(m for m in esn.modules() if hasattr(m, "weight_hh"))
>>> extractor.reservoirs[0].weight_hh is src.weight_hh
True
Source code in src/resdag/core/feature_extractor.py
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 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 | |
forward
¶
Map a feedback sequence to reservoir features.
| PARAMETER | DESCRIPTION |
|---|---|
feedback
|
Feedback signal of shape
TYPE:
|
*driving_inputs
|
Optional driving input of shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Reservoir features of shape |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If more than one driving input is supplied. |
Notes
With stateful=True (the default), state carries across calls until
reset_state is invoked. With stateful=False, every call
starts from zeros. When the extractor sits inside a
torch.nn.Sequential only feedback is passed, satisfying
the single-positional-input contract.
Source code in src/resdag/core/feature_extractor.py
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 | |
forward_stateless
¶
forward_stateless(
feedback: Tensor,
*driving_inputs: Tensor,
states: Iterable[Tensor] | None = None,
compile: bool = False
) -> tuple[Tensor, tuple[Tensor, ...]]
Extract features with explicit state, without changing stored states.
feedback and the optional driver have shape (batch, time, features). states contains one initial state per wrapped
reservoir; omit it to start every reservoir from zeros. The result is
(features, final_states). Pass final_states into a later call
to continue the same stream. States retain their autograd graphs;
detach them explicitly to truncate gradients between chunks.
compile=True opts into the layers' inference-only CUDA scan;
differentiable inputs or states keep the eager path.
Source code in src/resdag/core/feature_extractor.py
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 | |
reset_state
¶
reset_state(batch_size: int | None = None) -> None
Reset every wrapped reservoir's internal state.
| PARAMETER | DESCRIPTION |
|---|---|
batch_size
|
If given, materialise a zero state with this batch size on each
reservoir's device/dtype. If
TYPE:
|
See Also
on_epoch_start : Alias intended for use as an epoch-reset hook.
Source code in src/resdag/core/feature_extractor.py
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 | |
on_epoch_start
¶
on_epoch_start(batch_size: int | None = None) -> None
Epoch-reset hook: re-zero the stateful reservoir between epochs.
A thin, intent-revealing alias of reset_state meant to be
called at the top of each training epoch so a trajectory left over from
the previous epoch never bleeds into the next one.
| PARAMETER | DESCRIPTION |
|---|---|
batch_size
|
Forwarded to
TYPE:
|
Examples:
>>> for epoch in range(num_epochs):
... extractor.on_epoch_start()
... for batch in loader:
... ... # train the head
Source code in src/resdag/core/feature_extractor.py
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 | |
freeze
¶
freeze() -> ReservoirFeatureExtractor
Freeze the reservoir: set requires_grad=False on all its parameters.
| RETURNS | DESCRIPTION |
|---|---|
ReservoirFeatureExtractor
|
|
Source code in src/resdag/core/feature_extractor.py
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 | |
unfreeze
¶
unfreeze() -> ReservoirFeatureExtractor
Unfreeze the reservoir: set requires_grad=True on all its parameters.
| RETURNS | DESCRIPTION |
|---|---|
ReservoirFeatureExtractor
|
|
Source code in src/resdag/core/feature_extractor.py
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 | |
reservoir_input
¶
reservoir_input(
feature_size: int, dtype: dtype | None = None, *, device: device | str | None = None
) -> SymbolicData
Build a symbolic input tensor for a reservoir model.
Constructs an pytorch_symbolic.Input of shape (1, feature_size)
where the first axis is a placeholder for the time dimension (any
sequence length is accepted at call time).
| PARAMETER | DESCRIPTION |
|---|---|
feature_size
|
Number of features per timestep.
TYPE:
|
dtype
|
Tensor dtype. Defaults to
TYPE:
|
device
|
Device for the symbolic example, matching layers initialized there. |
| RETURNS | DESCRIPTION |
|---|---|
SymbolicTensor
|
Placeholder input with shape |
Examples:
>>> inp = reservoir_input(3)
>>> inp.shape
torch.Size([1, 1, 3])
Source code in src/resdag/core/__init__.py
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 | |
Recurrent state type¶
The exported ReservoirStates type is dict[str, torch.Tensor]. Keys identify
reservoirs in the owning graph; each value follows that cell's state layout.
The mapping returned by a model's state methods is accepted by its
forward_stateless method. State keys are specific to that model's wiring.