Reference
Core¶
The model class that turns a pytorch_symbolic graph into a stateful,
forecast-capable reservoir computer, plus the symbolic-input helpers used to
declare its entry points.
core
¶
Core Model¶
This module provides the main model class and input helpers for building
ESN architectures using the pytorch_symbolic library.
| CLASS | DESCRIPTION |
|---|---|
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.
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 :class:~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
reset_reservoirs
¶
Reset all reservoir layer states to zero.
This clears the internal hidden states of all :class:BaseReservoirLayer
modules in the model, preparing it for a new sequence.
Examples:
Source code in src/resdag/core/model.py
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
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
set_reservoir_states
¶
Set states of reservoir layers.
| PARAMETER | DESCRIPTION |
|---|---|
states
|
Dictionary mapping layer names to state tensors.
Names should match those returned by :meth:
TYPE:
|
strict
|
If
TYPE:
|
Notes
Each restored tensor is routed through
:meth:~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
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 | |
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:
Save with states and metadata:
See Also
load : Load model from file.
Source code in src/resdag/core/model.py
load
¶
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:
|
| WARNS | DESCRIPTION |
|---|---|
UserWarning
|
If |
Examples:
See Also
save : Save model to file. load_from_file : Class method for loading.
Source code in src/resdag/core/model.py
load_from_file
classmethod
¶
load_from_file(path: str | Path, model: 'ESNModel | None' = None, strict: bool = True, load_states: bool = False) -> '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:
|
| 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
save_full
¶
Serialize the entire model — architecture, weights, and reservoir states — to a single file.
Unlike :meth:save, which stores only the state_dict (so the
architecture must be re-created before :meth:load), this pickles the
whole model object, the pytorch_symbolic graph included. Restore it
with :meth: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 :meth:save instead.
Examples:
>>> model.save_full("model_full.pt", epoch=10)
>>> restored = ESNModel.load_full("model_full.pt") # no rebuild needed
>>> 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
load_full
classmethod
¶
load_full(path: str | Path, return_metadata: bool = False, map_location: Any = None) -> 'ESNModel | tuple[ESNModel, dict[str, Any]]'
Reconstruct a complete model saved with :meth:save_full.
No pre-built architecture is required — the model object, its symbolic graph, weights, and reservoir states are all restored from the file.
| PARAMETER | DESCRIPTION |
|---|---|
path
|
File path written by :meth: |
return_metadata
|
If True, return
TYPE:
|
map_location
|
Passed to
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 :meth: |
Warnings
Loads with weights_only=False, which unpickles arbitrary Python
objects. Only call this on files from a source you trust.
Notes
Accepts both :meth: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")
>>> model_cpu = ESNModel.load_full("gpu_model.pt", map_location="cpu")
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
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 | |
plot_model
¶
plot_model(show_shapes: bool = False, show_trainable: bool = False, rankdir: str = 'TB', save_path: str | Path | None = None, format: str = 'svg', **kwargs: Any) -> Any
Visualize model architecture as a graph.
| PARAMETER | DESCRIPTION |
|---|---|
show_shapes
|
Show tensor shapes on edges.
TYPE:
|
show_trainable
|
Show a padlock indicator (🔒 frozen / 🔓 trainable) on nodes that have learnable parameters.
TYPE:
|
rankdir
|
Graph layout direction.
TYPE:
|
save_path
|
Render and save to this path instead of displaying. |
format
|
Output format when
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Source or None
|
|
Notes
Requires the graphviz Python package and system binary.
pip install graphviz and apt install graphviz.
Source code in src/resdag/core/model.py
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 931 | |
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 :func: 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:
Synchronize and capture output:
With driving input:
Continue warming from a saved state:
See Also
forecast : Two-phase forecasting with warmup and generation. reset_reservoirs : Reset all reservoir states.
Source code in src/resdag/core/model.py
933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 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 | |
forecast
¶
forecast(warmup_inputs: tuple[Tensor, ...] | Tensor, forecast_inputs: tuple[Tensor, ...] | None = None, *, horizon: int, initial_feedback: Tensor | None = None, return_warmup: bool = False, reset: bool = True, compile: bool = False, no_grad: bool = True) -> Tensor | tuple[Tensor, ...]
Two-phase forecast: teacher-forced warmup + autoregressive generation.
Phase 1 (Warmup): Runs model with provided inputs to synchronize reservoir states with input dynamics (Echo State Property).
Phase 2 (Forecast): Autoregressive generation where feedback comes
from the model's own output while driving inputs (if any) are
supplied through forecast_inputs.
| PARAMETER | DESCRIPTION |
|---|---|
warmup_inputs
|
Warmup tensors of shape
TYPE:
|
forecast_inputs
|
Driver inputs for the autoregressive phase (feedback is provided
by the model's own output, so it is not part of this tuple).
TYPE:
|
horizon
|
Number of autoregressive steps to generate. Must be |
initial_feedback
|
Custom feedback of shape
TYPE:
|
return_warmup
|
If True, prepend warmup outputs to the result.
TYPE:
|
reset
|
If True, reservoir states are reset to
TYPE:
|
compile
|
If
TYPE:
|
no_grad
|
If True (default), the whole two-phase forecast runs under
:func:
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
torch.Tensor or tuple of torch.Tensor
|
For single-output models: tensor of shape
For multi-output models: tuple of tensors with the same structure. With |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If no warmup inputs are provided, if |
Notes
- Convention: first warmup element is always feedback (used for autoregression).
- For multi-output models, the first output is used as feedback.
- Feedback output dimension must match feedback input dimension.
- Every returned step is genuinely autoregressive: the loop feeds the
model its own previous output (seeded by
initial_feedbackor the last warmup output). No teacher-forced frame is included, sohorizon=1produces one real forecast step rather than echoing the warmup output, andreturn_warmup=Trueintroduces no duplicated frame at the warmup/forecast seam.
Driver time alignment. Training pairs (feedback_t, driver_t)
with target feedback_{t+1}. The forecast loop preserves that
pairing: step t feeds the current feedback together with
forecast_inputs[:, t] — the driver for that same step — and writes
the resulting prediction to slot t. The seed feedback corresponds
to the first step after the warmup window, so forecast_inputs must
hold the driver series beginning right after the warmup drivers (no
overlap) and provide at least horizon timesteps.
Flat single-step engine. The autoregressive loop is driven by a
flattened, graph-free step compiled once from the model graph (see
:mod:resdag.core._flat_inference) — numerically identical to the
per-step graph re-execution it replaces but without the per-step
nn.Module.__call__ dispatch and reservoir sequence-loop bookkeeping.
Because it calls each layer's forward (and the reservoir's
:meth:~resdag.layers.reservoirs.base_reservoir.BaseReservoirLayer.step_stateless)
directly, module forward/pre-hooks do not fire during the
autoregressive steps (the teacher-forced warmup still uses the full
graph path). The teacher-forced warmup runs the standard graph forward.
Differentiable rollout (no_grad=False). By default the rollout
is wrapped in :func:torch.no_grad for speed and memory. Pass
no_grad=False to keep the autograd graph so gradients flow through
the full BPTT unroll — the canonical building block for multi-step
training losses (scheduled sampling, tuning a trainable reservoir on
forecast error). Two things to keep in mind:
- Memory. The graph retains every intermediate from the warmup and all
horizonsteps, so peak memory grows linearly withwarmup_steps + horizon. Keep the horizon modest, or truncate it, when backpropagating. - Cross-seam gradients. For the gradient to flow from a forecast step
back through the warmup, the reservoir must not detach its carried
state between the warmup forward and the autoregressive loop. Set
reservoir.detach_state_between_calls = False(it defaults toTrue; the detach happens in :meth:~resdag.layers.reservoirs.base_reservoir.BaseReservoirLayer.forward). The autoregressive loop itself threads the state explicitly and never detaches, so gradients always flow within the forecast window.
Examples:
Simple feedback-only model:
>>> warmup_data = torch.randn(1, 50, 3)
>>> predictions = model.forecast(warmup_data, horizon=100)
>>> print(predictions.shape)
torch.Size([1, 100, 3])
Input-driven model:
>>> predictions = model.forecast(
... (warmup_feedback, warmup_driver),
... forecast_inputs=(future_driver,),
... horizon=100,
... )
Include warmup in output:
>>> full_output = model.forecast(
... warmup_data,
... horizon=100,
... return_warmup=True,
... )
>>> print(full_output.shape) # warmup_steps + horizon
torch.Size([1, 150, 3])
Differentiable multi-step rollout — train a trainable reservoir on a
forecast-error loss with BPTT. Build the reservoir trainable at
construction (trainable=True), then keep the warmup→forecast seam
graph by turning off cross-call detaching:
>>> reservoir = ESNLayer(reservoir_size, feedback_size, trainable=True)
>>> reservoir.detach_state_between_calls = False # keep the seam graph
>>> # ... wire ``reservoir`` into the model and readout ...
>>> opt = torch.optim.Adam(model.parameters(), lr=1e-3)
>>> for _ in range(steps):
... opt.zero_grad()
... preds = model.forecast(warmup_data, horizon=2, no_grad=False)
... loss = ((preds - target) ** 2).mean()
... loss.backward() # reaches reservoir + readout params
... opt.step()
See Also
warmup : Teacher-forced warmup only. reset_reservoirs : Reset reservoir states before forecasting.
Source code in src/resdag/core/model.py
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 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 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 | |
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
:meth: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 :func:
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
:meth:
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
1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 | |
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, **layer_kwargs: object)
Bases: Module
nn.Sequential-friendly reservoir feature extractor.
Wraps one reservoir layer (or a stack of them) as a plain
:class: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 :class: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 :meth: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 :class:
TYPE:
|
**layer_kwargs
|
Extra keyword arguments forwarded to every :class:
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 :class: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:
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 :class:~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
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) -> 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
:class:
TYPE:
|
trainable
|
Freeze/unfreeze toggle applied to the shared reservoir layers after
wrapping. Because the layers are shared, this also changes
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ReservoirFeatureExtractor
|
Extractor wrapping the model's reservoir layers by reference. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
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
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
The wrapped reservoirs are stateful: state carries across forward calls
until :meth:reset_state (or its :meth:on_epoch_start alias) is
invoked. When the extractor sits inside a :class:torch.nn.Sequential
only feedback is passed, satisfying the single-positional-input
contract.
Source code in src/resdag/core/feature_extractor.py
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
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 :meth: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 :meth:
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
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
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
reservoir_input
¶
Build a symbolic input tensor for a reservoir model.
Constructs an :func: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:
|
| RETURNS | DESCRIPTION |
|---|---|
SymbolicTensor
|
Placeholder input with shape |
Examples: