Skip to content

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

nn.Sequential-friendly adapter that packages reservoir layers as a drop-in feature extractor for ordinary torch.nn pipelines.

Input

Alias for pytorch_symbolic.Input for defining model inputs.

FUNCTION DESCRIPTION
reservoir_input

Convenience constructor for a per-feature symbolic input tensor with a placeholder time dimension. Preferred over hand-crafting ps.Input((T, F)) since the time dimension is purely a tracing hint inside reservoir models.

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.

Input module-attribute

Input = Input

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
def __init__(
    self,
    *,
    inputs: Mapping[str, SymbolicData] | None = None,
    outputs: Mapping[str, SymbolicData] | None = None,
    graph: nn.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, nn.Module] | None = None,
    output_transforms: Mapping[str, nn.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",
) -> None:
    super().__init__()
    self.washout = _washout(washout)
    self.resample_dt, self.resample_method = validate_resampling_options(
        resample_dt, resample_method
    )
    self._trajectory_context: dict[str, Any] | None = None
    object.__setattr__(self, "_trajectory_system", None)
    if preprocessing not in (
        None,
        "off",
        "minmax",
        "standard",
        "noncentered",
        "meanpreserving",
    ):
        raise ValueError("preprocessing must be a known normalization method, 'off', or None")
    self._preprocessing = None if preprocessing in (None, "off") else preprocessing
    if graph is not None:
        if inputs is not None or outputs is not None:
            raise ValueError("Supply graph= or named symbolic inputs/outputs, not both")
        backend = workflow_backend(graph)
        interface = backend.describe(graph)
        in_names = (
            input_names
            if input_names is not None
            else tuple(
                "input" if len(interface.input_widths) == 1 else f"input_{i}"
                for i in range(len(interface.input_widths))
            )
        )
        out_names = (
            output_names
            if output_names is not None
            else tuple(
                "output" if len(interface.output_widths) == 1 else f"output_{i}"
                for i in range(len(interface.output_widths))
            )
        )
    else:
        if input_names is not None or output_names is not None:
            raise ValueError("input_names/output_names belong to the graph= constructor")
        if (
            not isinstance(inputs, Mapping)
            or not inputs
            or not isinstance(outputs, Mapping)
            or not outputs
        ):
            raise ValueError("Provide non-empty named symbolic inputs and outputs, or graph=")
        if not all(
            isinstance(node, SymbolicData) for node in (*inputs.values(), *outputs.values())
        ):
            raise TypeError("inputs and outputs must map names to symbolic graph nodes")
        in_names, out_names = tuple(inputs), tuple(outputs)
        _port_names(in_names, len(inputs), "inputs")
        _port_names(out_names, len(outputs), "outputs")
        graph = ESNModel(tuple(inputs.values()), tuple(outputs.values()))
        backend = workflow_backend(graph)
        interface = backend.describe(graph)
    self.input_names = _port_names(in_names, len(interface.input_widths), "input_names")
    self.output_names = _port_names(out_names, len(interface.output_widths), "output_names")
    self.graph = graph
    self._backend = backend
    self._backend_interface_schema = interface.schema
    self._backend_schema = backend.checkpoint_schema(graph, interface)
    self._backend_references = interface.references
    self._input_widths = interface.input_widths
    self._output_widths = interface.output_widths
    self._prediction_leads = prediction_leads(prediction_lead, self.output_names)
    self._feedback = feedback_specs(feedback)
    self._feedback_plan(validate_widths=self._feedback is not None)
    method = cast(NormMethod, self._preprocessing or "standard")
    overrides = []
    for mapping, names in (
        (input_transforms, self.input_names),
        (output_transforms, self.output_names),
    ):
        if mapping is not None and (
            not isinstance(mapping, Mapping) or set(mapping) - set(names)
        ):
            raise ValueError(
                f"Transform override keys must be declared port names: {list(names)}"
            )
        overrides.append(dict(mapping or {}))
    self._custom_inputs = tuple(name in overrides[0] for name in self.input_names)
    self._custom_outputs = tuple(name in overrides[1] for name in self.output_names)
    originals = tuple(module for mapping in overrides for module in mapping.values())
    if any(not isinstance(module, nn.Module) for module in originals):
        raise TypeError("Transform overrides must be torch.nn.Module instances")
    validate_transform_ownership(graph, originals)
    for mapping, names, widths in (
        (overrides[0], self.input_names, self._input_widths),
        (overrides[1], self.output_names, self._output_widths),
    ):
        for name, width in zip(names, widths):
            if name in mapping:
                validate_custom_transform(mapping[name], width)
    self.input_scalers = nn.ModuleList(
        overrides[0].get(name, FittedNormalization(method)) for name in self.input_names
    )
    self.output_scalers = nn.ModuleList(
        overrides[1].get(name, FittedNormalization(method)) for name in self.output_names
    )
    reference = module_reference(graph)
    if reference is not None:
        self.input_scalers.to(device=reference.device, dtype=reference.dtype)
        self.output_scalers.to(device=reference.device, dtype=reference.dtype)
    self._transform_schema = self._custom_transform_schema()
    for group, masks, widths in (
        ("input", self._custom_inputs, self._input_widths),
        ("output", self._custom_outputs, self._output_widths),
    ):
        for index, (custom, width) in enumerate(zip(masks, widths)):
            if custom:
                with torch.inference_mode(False):
                    sample = (
                        torch.zeros(1, 3, width)
                        if reference is None
                        else reference.new_zeros(1, 3, width)
                    )
                self.register_buffer(f"_{group}_transform_sample_{index}", sample)
    for index, width in enumerate(self._input_widths):
        empty = torch.empty(0, width) if reference is None else reference.new_empty(0, width)
        self.register_buffer(f"_history_{index}", empty)
    self.register_buffer(
        "_fitted", torch.tensor(False, device=None if reference is None else reference.device)
    )
    self._fitted_flag = False
    self.register_load_state_dict_post_hook(self._synchronize_loaded_buffers)

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

prediction_leads: dict[str, int]

Physical target distances by public output name.

feedback property

feedback: tuple[Feedback, ...] | None

Explicit connections, or None for the automatic first-port route.

internal_readout_names property

internal_readout_names: tuple[str, ...]

Target keys for internal fitted heads, without exposing extra predictions.

save_formats property

save_formats: tuple[str, ...]

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
def forward(self, inputs: Streams) -> WorkflowOutput:
    """Predict in original units, retaining gradients and carried recurrent state."""
    self._require_scaling()
    values, was_2d = self._streams(inputs, self.input_names, self._input_widths, "inputs")
    return self._outputs(self.graph(*self._scaled_inputs(values)), was_2d)

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
def forward_stateless(
    self,
    inputs: Streams,
    *,
    states: Mapping[str, torch.Tensor] | None = None,
    compile: bool = False,
) -> tuple[WorkflowOutput, ReservoirStates]:
    """Predict original units with caller-managed recurrent states and gradients."""
    self._require_scaling()
    self._backend.validate_stateless(self.graph)
    from resdag.core._hooks import call_with_states, has_execution_hooks, state_paths

    if has_execution_hooks(self):
        return cast(
            tuple[WorkflowOutput, ReservoirStates],
            call_with_states(
                self, (inputs,), states, state_paths(self, "graph."), compile=compile
            ),
        )
    values, was_2d = self._streams(inputs, self.input_names, self._input_widths, "inputs")
    output, final = recurrent_graph(self.graph).forward_stateless(
        *self._scaled_inputs(values), states=states, compile=compile
    )
    return self._outputs(output, was_2d), final

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
def reset_state(self) -> None:
    """Start the next ordinary forward from the reservoirs' configured reset states."""
    recurrent_graph(self.graph).reset_reservoirs()

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
def get_state(self) -> 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.
    """
    return recurrent_graph(self.graph).get_state()

set_state

set_state(states: Mapping[str, Tensor], strict: bool = True) -> None

Restore ordinary-forward reservoir states, not delayed-rollout queues.

Source code in src/resdag/core/workflow.py
537
538
539
def set_state(self, states: Mapping[str, torch.Tensor], strict: bool = True) -> None:
    """Restore ordinary-forward reservoir states, not delayed-rollout queues."""
    recurrent_graph(self.graph).set_state(states, strict=strict)

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
def plot_model(
    self,
    *,
    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."""
    from resdag.core._diagram import plot_model

    self._validate_ports()
    return plot_model(
        self,
        save_path=save_path,
        format=format,
        show_shapes=show_shapes,
        show_trainable=show_trainable,
        rankdir=rankdir,
    )

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
def save(
    self,
    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.
    """
    destination = Path(path)
    suffix = destination.suffix.lower().lstrip(".")
    if format is not None and not isinstance(format, str):
        raise TypeError("format must be a string or None")
    selected = format.lower() if isinstance(format, str) else suffix or "pt"
    if selected not in self.save_formats or (suffix and suffix != selected):
        raise ValueError(f"Save format/suffix must agree and be one of {self.save_formats}")
    if not suffix:
        destination = destination.with_suffix(f".{selected}")
    if selected not in ("pt", "pth"):
        if trusted or metadata is not None or not include_state:
            raise ValueError(
                "trusted, metadata and include_state options apply to model checkpoints"
            )
        return self.plot_model(save_path=destination, format=selected, **diagram_options)
    if diagram_options:
        raise TypeError(
            f"Diagram options cannot be used with a model checkpoint: {list(diagram_options)}"
        )
    from resdag.artifacts import save_model

    self._validate_ports()
    return save_model(
        self, destination, include_state=include_state, trusted=trusted, metadata=metadata
    )

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
def tune(
    self,
    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.
    """
    from resdag.hpo import _require_optuna

    _require_optuna()
    from resdag.hpo.tuning import tune_model

    tune_model(
        self,
        training,
        targets,
        preset=preset,
        n_trials=n_trials,
        horizon=horizon,
        n_jobs=n_jobs,
        **options,
    )
    return self

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
def fit(
    self,
    training: Streams | Trajectory | Mapping[str, Trajectory],
    targets: Streams | Trajectory | Mapping[str, Trajectory] | None = None,
    *,
    readout_targets: Mapping[str, torch.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.
    """
    self._validate_ports()
    implicit = targets is None
    if is_trajectory(training) or has_trajectory_port(training):
        prepared = prepare_trajectory_ports(
            training,
            input_names=self.input_names,
            input_widths=self._input_widths,
            output_names=self.output_names,
            output_widths=self._output_widths,
            prediction_leads=self._prediction_leads,
            targets=targets,
            dt=self.resample_dt,
            method=self.resample_method,
        )
        reference = module_reference(self.graph)
        dtype = None if reference is None else reference.dtype
        device = None if reference is None else reference.device
        inputs = {
            name: torch.tensor(data, dtype=dtype, device=device)
            for name, data in zip(self.input_names, prepared.inputs)
        }
        labels = {
            name: torch.tensor(data, dtype=dtype, device=device)
            for name, data in zip(self.output_names, prepared.targets)
        }
        return self._fit_prepared(
            inputs,
            labels,
            supervised_start=prepared.supervised_start,
            supervised_stop=prepared.supervised_stop,
            implicit=implicit,
            trajectory_context=prepared.context,
            trajectory_system=prepared.output_systems,
            readout_targets=readout_targets,
        )
    if is_trajectory(targets) or has_trajectory_port(targets):
        raise TypeError(
            "Trajectory targets require clocked Trajectory training inputs; "
            "Tensor targets remain caller-aligned"
        )
    values, was_2d = self._streams(
        cast(Streams, training), self.input_names, self._input_widths, "training", finite=True
    )
    stop = values[0].shape[1]
    if implicit:
        if (
            len(values) != 1
            or len(self.output_names) != 1
            or self._input_widths != self._output_widths
        ):
            raise ValueError(
                "Implicit fitting requires one input/output of equal width; "
                "provide explicit named targets for custom graphs"
            )
        lead = self._prediction_leads[0]
        stop -= lead
        labels = {
            self.output_names[0]: (
                values[0][:, lead:].squeeze(0) if was_2d else values[0][:, lead:]
            )
        }
    else:
        target_values, targets_2d = self._streams(
            cast(Streams, targets),
            self.output_names,
            self._output_widths,
            "targets",
            finite=True,
        )
        if targets_2d != was_2d or any(
            value.shape[:2] != values[0].shape[:2] for value in target_values
        ):
            raise ValueError("Explicit targets must share training batch/time axes and layout")
        labels = {
            name: value.squeeze(0) if was_2d else value
            for name, value in zip(self.output_names, target_values)
        }
    return self._fit_prepared(
        cast(Streams, training),
        labels,
        supervised_start=0,
        supervised_stop=stop,
        implicit=implicit,
        readout_targets=readout_targets,
    )

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
def forecast(
    self,
    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.
    """
    self._require_scaling()
    if return_type not in ("auto", "tensor", "trajectory"):
        raise ValueError("return_type must be 'auto', 'tensor', or 'trajectory'")
    horizon = positive_step_count(horizon, "horizon")
    self._backend.validate_forecast(self.graph, compile=compile)
    validate_forecast_execution(self.graph, execution, compile=compile)
    from resdag.core._hooks import (
        eager_with_hooks,
        forecast_owner,
        has_execution_hooks,
        original_outputs,
    )

    owner = forecast_owner(self)
    hooked = has_execution_hooks(owner)
    if hooked:
        eager_with_hooks(compile)
        compile = False
    plan = self._feedback_plan()
    if any(not layer.is_fitted for _, layer in self._backend.fitted_readouts(self.graph)):
        raise RuntimeError(
            "Forecast requires fitted terminal readouts; call fit(training) first"
        )
    context = self._trajectory_context
    system = self._trajectory_system
    cached_history = history is None
    clocked_history = is_trajectory(history) or has_trajectory_port(history)
    if clocked_history:
        prepared = prepare_trajectory_port_history(
            history,
            input_names=self.input_names,
            input_widths=self._input_widths,
            output_names=self.output_names,
            output_widths=self._output_widths,
            context=context,
            dt=self.resample_dt,
            method=self.resample_method,
            output_systems=system,
        )
        context, system = prepared.context, prepared.output_systems
        reference = module_reference(self.graph)
        history = {
            name: torch.tensor(
                data,
                dtype=None if reference is None else reference.dtype,
                device=None if reference is None else reference.device,
            )
            for name, data in zip(self.input_names, prepared.inputs)
        }
    trajectory_output = return_type == "trajectory" or (
        return_type == "auto" and context is not None
    )
    if trajectory_output:
        if context is None or (not cached_history and not clocked_history):
            raise ValueError(
                "Trajectory output needs timestamped trajectory history or cached "
                "trajectory fitting history; pass a Trajectory or return_type='tensor'"
            )
        if set(context["outputs"]) != set(self.output_names):
            raise ValueError(
                "Trajectory output needs per-head target component metadata; "
                "fit Trajectory targets or choose return_type='tensor'"
            )
        trajectory_type()  # Optional dependency must fail before graph hooks execute.
    if history is None:
        if not self.is_fitted:
            raise RuntimeError("No cached history; provide history or call fit(training) first")
        history = {
            name: getattr(self, f"_history_{index}")
            for index, name in enumerate(self.input_names)
        }
    values, was_2d = self._streams(
        cast(Streams, history), self.input_names, self._input_widths, "history", finite=True
    )
    if values[0].shape[1] < plan.required_history:
        raise ValueError(
            f"history needs at least {plan.required_history} samples to seed all "
            "prediction leads and feedback delays"
        )
    driver_names = tuple(self.input_names[index] for index in plan.driver_indices)
    driver_widths = tuple(self._input_widths[index] for index in plan.driver_indices)
    steps = plan.future_steps(horizon)
    drivers: tuple[torch.Tensor, ...]
    if not driver_names:
        if future_inputs is not None:
            raise ValueError("This graph has no future driver inputs")
        drivers = ()
    elif future_inputs is None:
        if steps:
            raise ValueError(f"future_inputs requires driver keys {list(driver_names)}")
        drivers = tuple(values[index][:, :0] for index in plan.driver_indices)
    else:
        if is_trajectory(future_inputs) or has_trajectory_port(future_inputs):
            if context is None or (not cached_history and not clocked_history):
                raise ValueError(
                    "Trajectory drivers require timestamped or cached trajectory history; "
                    "new Tensor history has no absolute clock"
                )
            arrays = prepare_trajectory_port_drivers(
                future_inputs,
                input_names=driver_names,
                input_widths=driver_widths,
                last_time=context["clock"]["last_time"],
                dt=context["clock"]["dt"],
                steps=steps,
                method=self.resample_method,
                input_records=context["inputs"],
            )
            future_inputs = {
                name: torch.tensor(data, device=values[0].device, dtype=values[0].dtype)
                for name, data in zip(driver_names, arrays)
            }
        drivers, _ = self._streams(
            cast(Streams, future_inputs),
            driver_names,
            driver_widths,
            "future_inputs",
            finite=True,
            allow_empty=True,
        )
        if drivers[0].shape[0] != values[0].shape[0] or drivers[0].shape[1] < steps:
            raise ValueError(
                f"future_inputs must match the history batch and contain at least {steps} samples"
            )
    times = None
    if trajectory_output:
        assert context is not None
        times = trajectory_port_forecast_times(
            context,
            horizon,
            history_length=values[0].shape[1],
            warmup_lead=max(plan.leads),
            return_warmup=return_warmup,
        )
    default_route = (
        len(plan.routes) == 1
        and plan.routes[0] == FeedbackRoute(0, 0, 1)
        and all(lead == 1 for lead in plan.leads)
    )
    final_states = None
    output: ModelOutput
    with evaluating(owner):
        if not hooked and drivers and drivers[0].shape[1]:
            drivers = tuple(
                (
                    apply_transform(self.input_scalers[index], value)
                    if self._transform_active(output=False, index=index)
                    else value
                )
                for index, value in zip(plan.driver_indices, drivers)
            )
        if hooked:
            executor = ForecastSequenceExecutor(
                self.graph, execution, workflow=self, owner=owner
            )
            output, final_states = feedback_rollout(
                executor,
                values,
                drivers,
                plan,
                lambda route, value: value,
                horizon=horizon,
                return_warmup=return_warmup,
            )
        elif execution == "fast" and default_route and self._feedback_scaling_matches():
            output = self._backend.forecast(
                self.graph,
                self._scaled_inputs(values),
                drivers or None,
                horizon=horizon,
                return_warmup=return_warmup,
                compile=compile,
            )
        else:
            executor = ForecastSequenceExecutor(self.graph, execution, compile=compile)

            def bridge(route: FeedbackRoute, value: torch.Tensor) -> torch.Tensor:
                if self._transform_active(output=True, index=route.output_index):
                    value = apply_transform(
                        self.output_scalers[route.output_index], value, inverse=True
                    )
                if self._transform_active(output=False, index=route.input_index):
                    value = apply_transform(self.input_scalers[route.input_index], value)
                return value

            output, final_states = feedback_rollout(
                executor,
                self._scaled_inputs(values),
                drivers,
                plan,
                bridge,
                horizon=horizon,
                return_warmup=return_warmup,
            )
        result = (
            original_outputs(cast(tuple[torch.Tensor, ...], output), self.output_names, was_2d)
            if hooked
            else self._outputs(output, was_2d)
        )
    if not trajectory_output:
        if final_states is not None:
            self._commit_forecast_states(final_states)
        return result
    assert context is not None and times is not None
    # NumPy has no bfloat16 dtype. Conversion is confined to this explicit
    # CPU result boundary; tensor forecasts retain their device and dtype.
    result_values = (
        {self.output_names[0]: result} if isinstance(result, torch.Tensor) else result
    )
    result_arrays = {}
    for name, value in result_values.items():
        numpy_dtype = torch.float32 if value.dtype == torch.bfloat16 else value.dtype
        result_arrays[name] = value.detach().to(device="cpu", dtype=numpy_dtype).numpy()
    trajectory = forecast_trajectory_ports(
        result_arrays,
        context,
        output_names=self.output_names,
        output_systems=system,
        times=times,
    )
    if final_states is not None:
        self._commit_forecast_states(final_states)
    return trajectory

Feedback dataclass

Feedback(output: str, input: str, delay: int = 1)

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

ESNModel(*args: Any, **kwargs: Any)

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: list

outputs

List of model output tensors.

TYPE: list

output_shape

Shape(s) of model outputs.

TYPE: torch.Size or tuple of torch.Size

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
def __init__(self, *args: Any, **kwargs: Any) -> None:
    """Build the symbolic model and clear reservoir trace residue.

    `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.
    """
    super().__init__(*args, **kwargs)
    self.reset_reservoirs()

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
def forward_stateless(
    self,
    *inputs: torch.Tensor,
    states: Mapping[str, torch.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.
    """
    from resdag.core._hooks import call_with_states, has_execution_hooks

    plan = self._get_execution_plan(require_explicit_state=False)
    if has_execution_hooks(self):
        plan.validate_reservoir_visibility()
        plan.validate_inputs(inputs)
        return cast(
            tuple[ModelOutput, ReservoirStates],
            call_with_states(
                self,
                inputs,
                states,
                dict(zip(plan.reservoir_names, plan.reservoir_names)),
                compile=compile,
            ),
        )
    return plan.run_sequence(inputs, states, compile=compile)

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
def as_module(self, *, 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.
    """
    if stateful:
        _validate_unique_reservoir_invocations(self)
    else:
        self._get_execution_plan()
    return ReservoirModelModule(self, stateful=stateful)

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
def reset_reservoirs(self) -> 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)
    """
    for module in self.modules():
        if isinstance(module, BaseReservoirLayer):
            module.reset_state()

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: int DEFAULT: None

device

Target device for lazy initialisation.

TYPE: device DEFAULT: None

dtype

Target dtype for lazy initialisation.

TYPE: dtype DEFAULT: None

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
def set_random_reservoir_states(
    self,
    batch_size: int | None = None,
    device: torch.device | None = None,
    dtype: torch.dtype | None = None,
) -> None:
    """
    Set random states of all reservoir layers.

    Parameters
    ----------
    batch_size : int, optional
        If provided, lazily initialise each reservoir's state with this
        batch size before filling it with random values.
    device : torch.device, optional
        Target device for lazy initialisation.
    dtype : torch.dtype, optional
        Target dtype for lazy initialisation.

    Examples
    --------
    >>> model.set_random_reservoir_states()                # state must exist
    >>> model.set_random_reservoir_states(batch_size=4)    # lazy
    """
    for module in self.modules():
        if isinstance(module, BaseReservoirLayer):
            module.set_random_state(batch_size=batch_size, device=device, dtype=dtype)

get_reservoir_states

get_reservoir_states() -> dict[str, Tensor]

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
def get_reservoir_states(self) -> dict[str, torch.Tensor]:
    """
    Get current states of all reservoir layers.

    Returns
    -------
    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}")
    """
    states = {}
    for name, module in self.named_modules():
        if isinstance(module, BaseReservoirLayer) and module.state is not None:
            states[name] = module.state.clone()
    return states

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
def get_state(self) -> ReservoirStates:
    """Return named copies of all currently initialized recurrent states."""
    return self.get_reservoir_states()

set_state

set_state(states: Mapping[str, Tensor], strict: bool = True) -> None

Restore named recurrent states; names match forward_stateless.

Source code in src/resdag/core/model.py
456
457
458
def set_state(self, states: Mapping[str, torch.Tensor], strict: bool = True) -> None:
    """Restore named recurrent states; names match `forward_stateless`."""
    self.set_reservoir_states(dict(states), strict=strict)

set_reservoir_states

set_reservoir_states(states: dict[str, Tensor], strict: bool = True) -> None

Set states of reservoir layers.

PARAMETER DESCRIPTION
states

Dictionary mapping layer names to state tensors. Names should match those returned by get_reservoir_states.

TYPE: dict of str to torch.Tensor

strict

If True, raise a KeyError when the provided states dict is missing entries for any reservoir in the model or contains keys that don't match any reservoir. Set to False to silently ignore both kinds of mismatch (legacy behaviour).

TYPE: bool DEFAULT: True

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 strict=True and the keys of states do not exactly match the set of reservoir layer names in the model.

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
def set_reservoir_states(
    self,
    states: dict[str, torch.Tensor],
    strict: bool = True,
) -> None:
    """
    Set states of reservoir layers.

    Parameters
    ----------
    states : dict of str to torch.Tensor
        Dictionary mapping layer names to state tensors.
        Names should match those returned by `get_reservoir_states`.
    strict : bool, default=True
        If `True`, raise a `KeyError` when the provided `states`
        dict is missing entries for any reservoir in the model or
        contains keys that don't match any reservoir.  Set to `False`
        to silently ignore both kinds of mismatch (legacy behaviour).

    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
    ------
    KeyError
        If `strict=True` and the keys of `states` do not exactly
        match the set of reservoir layer names in the model.
    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
    -----
    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
    """
    import warnings

    reservoir_names = {
        name for name, module in self.named_modules() if isinstance(module, BaseReservoirLayer)
    }
    provided = set(states.keys())

    if strict:
        missing = reservoir_names - provided
        extra = provided - reservoir_names
        if missing or extra:
            parts: list[str] = []
            if missing:
                parts.append(f"missing keys for reservoirs: {sorted(missing)}")
            if extra:
                parts.append(f"unexpected keys not matching any reservoir: {sorted(extra)}")
            raise KeyError("set_reservoir_states(strict=True): " + "; ".join(parts))

    for name, module in self.named_modules():
        if isinstance(module, BaseReservoirLayer) and name in states:
            state = states[name]
            ref_device, ref_dtype = module.reference_device_dtype()
            if state.device != ref_device or state.dtype != ref_dtype:
                warnings.warn(
                    f"set_reservoir_states: state for reservoir '{name}' was "
                    f"coerced from (device={state.device}, dtype={state.dtype}) to "
                    f"(device={ref_device}, dtype={ref_dtype}) to match the "
                    f"target reservoir.",
                    UserWarning,
                    stacklevel=2,
                )
                state = state.to(device=ref_device, dtype=ref_dtype)
            # set_state clones and validates the tensor via the cell's
            # state-shape contract.
            module.set_state(state)

save

save(path: str | Path, include_states: bool = False, **metadata: Any) -> None

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.

TYPE: str or Path

include_states

If True, also save current reservoir states. Only reservoirs whose state is non-None are persisted (see get_reservoir_states); reservoirs that are still lazily-uninitialised at save time — e.g. a model saved before any warmup — are omitted from the checkpoint. load restores the saved states after resetting current recurrent state, so omitted reservoirs resume from an uninitialized state.

TYPE: bool DEFAULT: False

**metadata

Additional metadata to store with the model (e.g., training info).

TYPE: Any DEFAULT: {}

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
def save(
    self,
    path: str | Path,
    include_states: bool = False,
    **metadata: Any,
) -> None:
    """
    Save model weights and optionally reservoir states.

    Parameters
    ----------
    path : str or Path
        File path to save the model. Parent directories are created
        if they don't exist.
    include_states : bool, default=False
        If True, also save current reservoir states. Only reservoirs whose
        state is non-`None` are persisted (see
        `get_reservoir_states`); reservoirs that are still
        lazily-uninitialised at save time — e.g. a model saved before any
        warmup — are omitted from the checkpoint. `load` restores the
        saved states after resetting current recurrent state, so omitted
        reservoirs resume from an uninitialized state.
    **metadata
        Additional metadata to store with the model (e.g., training info).

    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.
    """
    save_checkpoint(self, path, include_states, metadata)

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.

TYPE: str or Path

strict

If True, strictly enforce that state_dict keys match.

TYPE: bool DEFAULT: True

load_states

If True, also load reservoir states if available. States are restored tolerantly (strict=False): because save only persists reservoirs whose state is non-None, a checkpoint may legitimately omit some reservoir keys (e.g. one saved before warmup). Current states are reset first; reservoirs absent from the checkpoint start uninitialized.

TYPE: bool DEFAULT: False

map_location

Passed to torch.load. Use "cpu" to load a checkpoint written on a GPU on a machine without that GPU.

TYPE: optional DEFAULT: None

WARNS DESCRIPTION
UserWarning

If load_states=True but no states are found in checkpoint.

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
def load(
    self,
    path: str | Path,
    strict: bool = True,
    load_states: bool = False,
    map_location: Any = None,
) -> None:
    """
    Load model weights from file.

    Parameters
    ----------
    path : str or Path
        File path to load from.
    strict : bool, default=True
        If True, strictly enforce that state_dict keys match.
    load_states : bool, default=False
        If True, also load reservoir states if available. States are
        restored tolerantly (`strict=False`): because
        `save` only persists reservoirs whose state is non-`None`,
        a checkpoint may legitimately omit some reservoir keys (e.g. one
        saved before warmup). Current states are reset first; reservoirs
        absent from the checkpoint start uninitialized.
    map_location : optional
        Passed to `torch.load`. Use `"cpu"` to load a checkpoint
        written on a GPU on a machine without that GPU.

    Warns
    -----
    UserWarning
        If `load_states=True` but no states are found in checkpoint.

    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.
    """
    load_checkpoint(self, path, strict, load_states, map_location)

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.

TYPE: str or Path

model

Model instance to load weights into. Required.

TYPE: ESNModel DEFAULT: None

strict

If True, strictly enforce state_dict key matching.

TYPE: bool DEFAULT: True

load_states

If True, also load reservoir states.

TYPE: bool DEFAULT: False

map_location

Storage-device remapping forwarded to load.

TYPE: optional DEFAULT: None

RETURNS DESCRIPTION
ESNModel

The model instance with loaded weights.

RAISES DESCRIPTION
ValueError

If model is None.

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
@classmethod
def load_from_file(
    cls,
    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.

    Parameters
    ----------
    path : str or Path
        File path to load from.
    model : ESNModel
        Model instance to load weights into. Required.
    strict : bool, default=True
        If True, strictly enforce state_dict key matching.
    load_states : bool, default=False
        If True, also load reservoir states.
    map_location : optional
        Storage-device remapping forwarded to `load`.

    Returns
    -------
    ESNModel
        The model instance with loaded weights.

    Raises
    ------
    ValueError
        If `model` is None.

    Examples
    --------
    >>> model = create_my_model()  # Create architecture
    >>> model = ESNModel.load_from_file("weights.pt", model=model)
    """
    if model is None:
        raise ValueError("model argument is required")

    model.load(path, strict=strict, load_states=load_states, map_location=map_location)
    return model

save_full

save_full(path: str | Path, **metadata: Any) -> None

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.

TYPE: str or Path

**metadata

Additional metadata stored alongside the model (e.g. training info).

TYPE: Any DEFAULT: {}

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
def save_full(
    self,
    path: str | Path,
    **metadata: Any,
) -> None:
    """
    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.

    Parameters
    ----------
    path : str or Path
        File path to save to. Parent directories are created if needed.
    **metadata
        Additional metadata stored alongside the model (e.g. training info).

    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).
    """
    save_full_model(self, path, metadata)

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 save_full.

TYPE: str or Path

return_metadata

If True, return (model, metadata) instead of just the model.

TYPE: bool DEFAULT: False

map_location

Passed to torch.load to remap storage devices — e.g. "cpu" to load a GPU-saved model on a CPU-only machine.

TYPE: optional DEFAULT: None

trusted

Required explicit opt-in to unpickle executable Python. Prefer Model.save and resdag.load for portable restricted artifacts.

TYPE: bool DEFAULT: False

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 save (rebuild the architecture and use load / load_from_file for those).

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
@classmethod
def load_full(
    cls,
    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`.

    Parameters
    ----------
    path : str or Path
        File path written by `save_full`.
    return_metadata : bool, default=False
        If True, return `(model, metadata)` instead of just the model.
    map_location : optional
        Passed to `torch.load` to remap storage devices — e.g.
        `"cpu"` to load a GPU-saved model on a CPU-only machine.
    trusted : bool, default=False
        Required explicit opt-in to unpickle executable Python. Prefer
        `Model.save` and `resdag.load` for portable restricted artifacts.

    Returns
    -------
    ESNModel or tuple of (ESNModel, dict)
        The reconstructed model, optionally paired with its metadata dict.

    Raises
    ------
    ValueError
        If the file does not contain a whole model — e.g. it is a
        state-dict checkpoint from `save` (rebuild the architecture
        and use `load` / `load_from_file` for those).

    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.
    """
    return load_full_model(cls, path, return_metadata, map_location, trusted=trusted)

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
def plot_model(
    self,
    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.
    """
    from resdag.core._diagram import plot_model

    return plot_model(
        self,
        save_path=save_path,
        format=format,
        show_shapes=show_shapes,
        show_trainable=show_trainable,
        rankdir=rankdir,
        **kwargs,
    )

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 (batch, timesteps, features). Convention: first input is feedback, remaining are drivers.

TYPE: Tensor DEFAULT: ()

return_outputs

If True, return model outputs during warmup.

TYPE: bool DEFAULT: False

reset

If True, reservoir states are reset to None before the warmup pass. Set to False only if you want to continue from a previously saved state — typical workflows always reset.

TYPE: bool DEFAULT: True

no_grad

If True (default), the warmup pass runs under torch.no_grad — no autograd graph is built and behaviour/performance are identical to the historical @torch.no_grad() decorator. Set False to keep the graph so the teacher-forced pass is part of a wider backpropagation (e.g. BPTT over the warmup→forecast seam).

For gradients to flow across the warmup→forecast boundary the reservoir must also keep its carried state attached: set reservoir.detach_state_between_calls = False (it defaults to True, which detaches the stored state at every forward call — see resdag.layers.reservoirs.base_reservoir.BaseReservoirLayer). Note that no_grad=False retains the full warmup graph in memory, so cost grows with the warmup length.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
torch.Tensor or tuple of torch.Tensor or None

If return_outputs=True: the model output of shape (batch, timesteps, output_dim) for a single-output model, or a tuple of such tensors for a multi-output model. Otherwise: None (only internal state is updated).

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
def warmup(
    self,
    *inputs: torch.Tensor,
    return_outputs: bool = False,
    reset: bool = True,
    no_grad: bool = True,
) -> torch.Tensor | tuple[torch.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).

    Parameters
    ----------
    *inputs : torch.Tensor
        Input tensors of shape `(batch, timesteps, features)`.
        Convention: first input is feedback, remaining are drivers.
    return_outputs : bool, default=False
        If True, return model outputs during warmup.
    reset : bool, default=True
        If True, reservoir states are reset to `None` before the
        warmup pass.  Set to `False` only if you want to continue
        from a previously saved state — typical workflows always reset.
    no_grad : bool, default=True
        If True (default), the warmup pass runs under `torch.no_grad`
        — no autograd graph is built and behaviour/performance are identical
        to the historical `@torch.no_grad()` decorator.  Set `False` to
        keep the graph so the teacher-forced pass is part of a wider
        backpropagation (e.g. BPTT over the warmup→forecast seam).

        For gradients to flow *across* the warmup→forecast boundary the
        reservoir must also keep its carried state attached: set
        `reservoir.detach_state_between_calls = False` (it defaults to
        `True`, which detaches the stored state at every forward call —
        see `resdag.layers.reservoirs.base_reservoir.BaseReservoirLayer`).
        Note that `no_grad=False` retains the full warmup graph in memory,
        so cost grows with the warmup length.

    Returns
    -------
    torch.Tensor or tuple of torch.Tensor or None
        If `return_outputs=True`: the model output of shape
        `(batch, timesteps, output_dim)` for a single-output model, or a
        tuple of such tensors for a multi-output model.
        Otherwise: None (only internal state is updated).

    Raises
    ------
    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.
    """
    if len(inputs) == 0:
        raise ValueError("At least one input (feedback) is required")

    if reset:
        self.reset_reservoirs()

    with _grad_context(no_grad):
        output = self(*inputs)

    return output if return_outputs else None

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 (batch, time, features). For a driven model pass (feedback, driver1, ...) with matching batch/time axes. Empty history is allowed only with initial_feedback; with reset=False this continues saved reservoir states.

TYPE: torch.Tensor or tuple of torch.Tensor

forecast_inputs

Future drivers beginning immediately after the warmup drivers. Driver d[t] pairs with input feedback x[t] to predict x[t+1]. The default needs horizon - 1 driver samples because warmup already supplied the driver for the first prediction. horizon=1 needs no future drivers. Explicit initial_feedback and alignment="legacy" need horizon future driver samples. Extra trailing driver samples are ignored.

TYPE: torch.Tensor or tuple of torch.Tensor DEFAULT: None

horizon

Number of predictions, a positive integer. Zero is rejected; use a normal forward/warmup call when no future predictions are needed.

TYPE: int

initial_feedback

A distinct additional observed input of shape (batch, 1, features) consumed after the complete warmup. Slot zero predicts the sample after this seed. Do not pass the last warmup observation again: that would consume it twice. This also seeds an empty warmup continuation.

TYPE: Tensor DEFAULT: None

return_warmup

Prepend historical predictions. With default alignment, the last warmup prediction is already forecast slot zero, so the full result has warmup_steps - 1 + horizon samples with no duplicate seam. With an explicit seed or legacy alignment it has warmup_steps + horizon samples.

TYPE: bool DEFAULT: False

reset

Reset reservoir states before warmup. False continues current states.

TYPE: bool DEFAULT: True

compile

Compile the flat autoregressive executor when supported, falling back to eager execution with a warning if compilation fails. Incompatible with no_grad=False.

TYPE: bool DEFAULT: False

no_grad

Disable autograd for inference. False makes the warmup and rollout differentiable. For gradients through carried warmup state, set each reservoir's detach_state_between_calls=False. Memory grows with history and horizon length.

TYPE: bool DEFAULT: True

alignment

"next" predicts the immediate unseen sample. "legacy" reproduces the old low-level convention, which consumed the final warmup prediction before returning slot zero and therefore skipped the immediate unseen sample. Pair it with prepare_esn_data(..., alignment="legacy") to reproduce old runs.

TYPE: ('next', 'legacy') DEFAULT: "next"

RETURNS DESCRIPTION
torch.Tensor or tuple of torch.Tensor

(batch, horizon, output_features) per output head, or the longer sequence described above when return_warmup=True. The first output head supplies autoregressive feedback and must match the feedback input width.

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
def forecast(
    self,
    warmup_inputs: tuple[torch.Tensor, ...] | torch.Tensor,
    forecast_inputs: tuple[torch.Tensor, ...] | torch.Tensor | None = None,
    *,
    horizon: int,
    initial_feedback: torch.Tensor | None = None,
    return_warmup: bool = False,
    reset: bool = True,
    compile: bool = False,
    no_grad: bool = True,
    alignment: ForecastAlignment = "next",
) -> torch.Tensor | tuple[torch.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.

    Parameters
    ----------
    warmup_inputs : torch.Tensor or tuple of torch.Tensor
        Observed history, shaped `(batch, time, features)`. For a driven
        model pass `(feedback, driver1, ...)` with matching batch/time axes.
        Empty history is allowed only with `initial_feedback`; with
        `reset=False` this continues saved reservoir states.
    forecast_inputs : torch.Tensor or tuple of torch.Tensor, optional
        Future drivers beginning immediately after the warmup drivers.
        Driver `d[t]` pairs with input feedback `x[t]` to predict
        `x[t+1]`. The default needs `horizon - 1` driver samples because
        warmup already supplied the driver for the first prediction.
        `horizon=1` needs no future drivers. Explicit `initial_feedback`
        and `alignment="legacy"` need `horizon` future driver samples.
        Extra trailing driver samples are ignored.
    horizon : int
        Number of predictions, a positive integer. Zero is rejected; use a
        normal forward/warmup call when no future predictions are needed.
    initial_feedback : torch.Tensor, optional
        A distinct additional observed input of shape `(batch, 1, features)`
        consumed *after* the complete warmup. Slot zero predicts the sample
        after this seed. Do not pass the last warmup observation again: that
        would consume it twice. This also seeds an empty warmup continuation.
    return_warmup : bool, default=False
        Prepend historical predictions. With default alignment, the last
        warmup prediction is already forecast slot zero, so the full result
        has `warmup_steps - 1 + horizon` samples with no duplicate seam.
        With an explicit seed or legacy alignment it has
        `warmup_steps + horizon` samples.
    reset : bool, default=True
        Reset reservoir states before warmup. False continues current states.
    compile : bool, default=False
        Compile the flat autoregressive executor when supported, falling
        back to eager execution with a warning if compilation fails.
        Incompatible with `no_grad=False`.
    no_grad : bool, default=True
        Disable autograd for inference. False makes the warmup and rollout
        differentiable. For gradients through carried warmup state, set
        each reservoir's `detach_state_between_calls=False`. Memory grows
        with history and horizon length.
    alignment : {"next", "legacy"}, default="next"
        `"next"` predicts the immediate unseen sample. `"legacy"`
        reproduces the old low-level convention, which consumed the final
        warmup prediction before returning slot zero and therefore skipped
        the immediate unseen sample. Pair it with
        `prepare_esn_data(..., alignment="legacy")` to reproduce old runs.

    Returns
    -------
    torch.Tensor or tuple of torch.Tensor
        `(batch, horizon, output_features)` per output head, or the longer
        sequence described above when `return_warmup=True`. The first
        output head supplies autoregressive feedback and must match the
        feedback input width.

    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.
    """
    validate_fast_plan(self._get_execution_plan())
    warmup_inputs, drivers, horizon, boundary = prepare_forecast_inputs(
        warmup_inputs,
        forecast_inputs,
        num_inputs=len(self.inputs),
        horizon=horizon,
        initial_feedback=initial_feedback,
        alignment=alignment,
    )
    if compile and not no_grad:
        raise ValueError(
            "forecast(compile=True) is incompatible with no_grad=False: the "
            "reduce-overhead/cudagraph step path does not support autograd. "
            "Use no_grad=False with compile=False for a differentiable rollout."
        )

    output_shape = self.output_shape
    multi_output = isinstance(output_shape, tuple) and isinstance(output_shape[0], torch.Size)
    feedback_dim = warmup_inputs[0].shape[-1]
    feedback_output_dim = output_shape[0][-1] if multi_output else output_shape[-1]
    if feedback_output_dim != feedback_dim:
        raise ValueError(
            "forecast(): feedback dimension mismatch. "
            f"Feedback input has {feedback_dim} features but the model output "
            f"used as feedback has {feedback_output_dim} features. "
            "For autoregressive forecasting the first output must match the feedback input dimension."
        )

    warmup_outputs = self.warmup(
        *warmup_inputs, return_outputs=True, reset=reset, no_grad=no_grad
    )
    assert warmup_outputs is not None
    outputs = warmup_outputs if isinstance(warmup_outputs, tuple) else (warmup_outputs,)
    assert all(isinstance(out, torch.Tensor) for out in outputs)
    with _grad_context(no_grad):
        seed = initial_feedback if initial_feedback is not None else outputs[0][:, -1:, :]
        steps = horizon - int(boundary)
        if steps:
            flat = self._get_flat_step()
            states: list[torch.Tensor] = []
            for reservoir in flat.reservoir_layers:
                if reservoir.state is None:
                    reservoir._maybe_init_state(
                        warmup_inputs[0].shape[0], seed.device, seed.dtype
                    )
                assert reservoir.state is not None
                states.append(reservoir.state)
            forecast_buffers, states = rollout(
                flat,
                seed,
                drivers,
                states,
                steps,
                [out.shape[-1] for out in outputs],
                no_grad=no_grad,
                compile=compile,
                output_templates=outputs,
            )
            for reservoir, state in zip(flat.reservoir_layers, states):
                if reservoir.detach_state_between_calls and state.grad_fn is not None:
                    reservoir.state = state.detach().clone()
                else:
                    reservoir.state = state.clone()
        else:
            forecast_buffers = [out[:, :0, :] for out in outputs]

        predictions = []
        for warm, generated in zip(outputs, forecast_buffers):
            if boundary:
                generated = torch.cat((warm[:, -1:, :], generated), dim=1)
            if return_warmup:
                prefix = warm[:, :-1, :] if boundary else warm
                generated = torch.cat((prefix, generated), dim=1)
            predictions.append(generated)
        return tuple(predictions) if multi_output else predictions[0]

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 (batch, T, feedback_dim). It is both the source of every teacher-forced window and the value returned on observed segments.

TYPE: Tensor

*driver_series

Exogenous driver series, one per driver input of the model, each of shape (batch, T, driver_dim) spanning the full timeline. Omit for feedback-only models. Unlike forecast (which takes separate warmup and forecast_inputs driver tuples), here each driver covers the whole T-step timeline and is sliced internally per cycle.

TYPE: Tensor DEFAULT: ()

predict_len

Length P of each autonomous forecast window (the gap to fill). Must be >= 1.

TYPE: (int, keyword - only)

teacher_len

Length F of each teacher-forced re-synchronization window. Must be >= 1. Longer windows re-sync more reliably; shorter windows observe less of the signal.

TYPE: (int, keyword - only)

warmup_len

Length W of the initial teacher-forced window. Defaults to teacher_len.

TYPE: int DEFAULT: None

reset

If True, reservoir states are reset before the first window. Set False to continue from the current (already warmed) state.

TYPE: bool DEFAULT: True

return_mask

If True, also return a 1-D boolean mask of length T that is True where the reconstruction is a real value and False where it is a model forecast (see Returns).

TYPE: bool DEFAULT: False

no_grad

If True (default), every cycle runs under torch.no_grad — graph-free and identical to the historical @torch.no_grad() decorator. Set False to make the gap-fill reconstruction differentiable: the value threaded into the reconstruction on every forecast segment carries an autograd graph, so a loss over the gaps (reconstruction[:, ~mask]) can be back-propagated through the BPTT unroll of each window into the trainable reservoir and readout parameters. The flag is threaded into the per-cycle forecast calls; the same memory cost and reservoir.detach_state_between_calls caveats documented on forecast apply, multiplied across cycles (state is carried across windows, so detaching it severs gradients window-to-window).

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
reconstruction

Reconstructed series of shape (batch, T, feedback_dim): real values on observed segments, forecasts on the gaps.

TYPE: Tensor

mask

Only if return_mask=True. Boolean tensor of shape (T,), True where the step is a real value (a teacher-forced window, or the untouched trailing remainder copied verbatim from series) and False where it is a model forecast.

TYPE: Tensor

RAISES DESCRIPTION
ValueError

If series is not 3-D, if predict_len/teacher_len/ warmup_len are not positive, if the number of driver_series does not match the model's drivers, if any driver does not span T steps, or if series is too short for even one cycle.

Notes
  • The forecast steps to score are exactly reconstruction[:, ~mask] against series[:, ~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
def windowed_forecast(
    self,
    series: torch.Tensor,
    *driver_series: torch.Tensor,
    predict_len: int,
    teacher_len: int,
    warmup_len: int | None = None,
    reset: bool = True,
    return_mask: bool = False,
    no_grad: bool = True,
) -> torch.Tensor | tuple[torch.Tensor, torch.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`):

    ```text
    [== 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.

    Parameters
    ----------
    series : torch.Tensor
        Ground-truth feedback series of shape `(batch, T, feedback_dim)`.
        It is both the source of every teacher-forced window and the value
        returned on observed segments.
    *driver_series : torch.Tensor
        Exogenous driver series, one per driver input of the model, each of
        shape `(batch, T, driver_dim)` spanning the full timeline.  Omit
        for feedback-only models.  Unlike `forecast` (which takes
        *separate* warmup and `forecast_inputs` driver tuples), here each
        driver covers the whole `T`-step timeline and is sliced internally
        per cycle.
    predict_len : int, keyword-only
        Length `P` of each autonomous forecast window (the gap to fill).
        Must be `>= 1`.
    teacher_len : int, keyword-only
        Length `F` of each teacher-forced re-synchronization window.
        Must be `>= 1`.  Longer windows re-sync more reliably; shorter
        windows observe less of the signal.
    warmup_len : int, optional
        Length `W` of the initial teacher-forced window.  Defaults to
        `teacher_len`.
    reset : bool, default=True
        If True, reservoir states are reset before the first window.  Set
        False to continue from the current (already warmed) state.
    return_mask : bool, default=False
        If True, also return a 1-D boolean mask of length `T` that is
        True where the reconstruction is a real value and False where it is
        a model forecast (see Returns).
    no_grad : bool, default=True
        If True (default), every cycle runs under `torch.no_grad` —
        graph-free and identical to the historical `@torch.no_grad()`
        decorator.  Set `False` to make the gap-fill reconstruction
        **differentiable**: the value threaded into the reconstruction on
        every forecast segment carries an autograd graph, so a loss over the
        gaps (`reconstruction[:, ~mask]`) can be back-propagated through the
        BPTT unroll of each window into the trainable reservoir and readout
        parameters.  The flag is threaded into the per-cycle `forecast`
        calls; the same memory cost and
        `reservoir.detach_state_between_calls` caveats documented on
        `forecast` apply, multiplied across cycles (state is carried
        across windows, so detaching it severs gradients window-to-window).

    Returns
    -------
    reconstruction : torch.Tensor
        Reconstructed series of shape `(batch, T, feedback_dim)`: real
        values on observed segments, forecasts on the gaps.
    mask : torch.Tensor
        Only if `return_mask=True`.  Boolean tensor of shape `(T,)`,
        True where the step is a real value (a teacher-forced window, or the
        untouched trailing remainder copied verbatim from `series`) and
        False where it is a model forecast.

    Raises
    ------
    ValueError
        If `series` is not 3-D, if `predict_len`/`teacher_len`/
        `warmup_len` are not positive, if the number of `driver_series`
        does not match the model's drivers, if any driver does not span
        `T` steps, or if `series` is too short for even one cycle.

    Notes
    -----
    - The forecast steps to score are exactly `reconstruction[:, ~mask]`
      against `series[:, ~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.
    """
    if series.dim() != 3:
        raise ValueError(
            f"series must be 3-D (batch, T, feedback_dim); got shape {tuple(series.shape)}."
        )
    predict_len = positive_step_count(predict_len, "predict_len")
    teacher_len = positive_step_count(teacher_len, "teacher_len")
    if warmup_len is None:
        warmup_len = teacher_len
    warmup_len = positive_step_count(warmup_len, "warmup_len")

    num_drivers = len(driver_series)
    expected_drivers = len(self.inputs) - 1
    if num_drivers != expected_drivers:
        raise ValueError(
            f"model has {expected_drivers} driver input(s) but {num_drivers} "
            f"driver_series were given. Pass one full-timeline driver series per "
            f"driver input (the feedback is supplied by `series`)."
        )

    _, total_steps, _ = series.shape
    for i, driver in enumerate(driver_series):
        if driver.dim() != 3:
            raise ValueError(
                f"driver_series[{i}] must be 3-D (batch, T, driver_dim); "
                f"got shape {tuple(driver.shape)}."
            )
        if driver.shape[1] != total_steps:
            raise ValueError(
                f"driver_series[{i}] spans {driver.shape[1]} steps but series spans "
                f"{total_steps}; drivers must cover the full timeline."
            )

    # ``no_grad`` is also threaded into each per-cycle ``forecast`` below; the
    # context here additionally covers the in-place reconstruction writes so
    # that, when differentiable, the forecast segments graft their autograd
    # graph onto the (cloned) reconstruction via ``CopySlices``.
    reconstruction = series.clone()
    mask = torch.ones(total_steps, dtype=torch.bool, device=series.device)

    pos = 0
    window_len = warmup_len
    ran_a_cycle = False
    with _grad_context(no_grad):
        while True:
            teacher_end = pos + window_len
            # Stop once a full re-sync window leaves no room to forecast. The
            # guard guarantees ``teacher_end < total_steps`` below, so the gap
            # (clamped to whatever remains) is always at least one step.
            if teacher_end >= total_steps:
                break
            gap = min(predict_len, total_steps - teacher_end)

            teacher_window = series[:, pos:teacher_end, :]
            if num_drivers:
                warmup_inputs: tuple[torch.Tensor, ...] = (
                    teacher_window,
                    *(d[:, pos:teacher_end, :] for d in driver_series),
                )
                forecast_inputs: tuple[torch.Tensor, ...] | None = tuple(
                    d[:, teacher_end : teacher_end + gap, :] for d in driver_series
                )
            else:
                warmup_inputs = (teacher_window,)
                forecast_inputs = None

            # Generate one additional prediction so the final gap sample is
            # consumed too. Its value is discarded, but this advances state
            # through the entire gap before the next observed window.
            full = self.forecast(
                warmup_inputs,
                forecast_inputs=forecast_inputs,
                horizon=gap + 1,
                reset=reset and not ran_a_cycle,
                no_grad=no_grad,
            )
            feedback_full = full[0] if isinstance(full, tuple) else full
            gap_preds = feedback_full[:, :gap, :]
            reconstruction[:, teacher_end : teacher_end + gap, :] = gap_preds
            mask[teacher_end : teacher_end + gap] = False

            ran_a_cycle = True
            pos = teacher_end + gap
            window_len = teacher_len

    if not ran_a_cycle:
        raise ValueError(
            f"series length ({total_steps}) is too short for even one cycle: the "
            f"initial warmup window (warmup_len={warmup_len}) leaves no room to "
            f"forecast (need at least warmup_len + 1 = {warmup_len + 1} steps; the "
            f"final gap is clamped to whatever remains)."
        )

    if return_mask:
        return reconstruction, mask
    return reconstruction

ReservoirModelModule

ReservoirModelModule(model: Module, *, stateful: bool = False)

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
def __init__(self, model: torch.nn.Module, *, stateful: bool = False) -> None:
    super().__init__()
    if not all(
        callable(getattr(model, name, None))
        for name in ("forward_stateless", "reset_reservoirs", "get_state", "set_state")
    ):
        raise TypeError("model must implement reservoir model execution and state methods")
    self.model = model
    self.stateful = stateful

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
def forward(self, *inputs: torch.Tensor) -> ModelOutput:
    """Predict independent sequences from each reservoir's configured reset state."""
    if self.stateful:
        output: ModelOutput = self.model(*inputs)
        return output
    output, _ = self._model_api.forward_stateless(*inputs)
    return output

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
def forward_stateless(
    self,
    *inputs: torch.Tensor,
    states: Mapping[str, torch.Tensor] | None = None,
    compile: bool = False,
) -> tuple[ModelOutput, ReservoirStates]:
    """Predict with explicitly supplied and returned reservoir states."""
    return self._model_api.forward_stateless(*inputs, states=states, compile=compile)

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
def reset_state(self) -> None:
    """Reset the source model's stored states for stateful streaming."""
    self._model_api.reset_reservoirs()

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
def get_state(self) -> ReservoirStates:
    """Return copies of the wrapped model's initialized streaming states."""
    return self._model_api.get_state()

set_state

set_state(states: Mapping[str, Tensor], strict: bool = True) -> None

Restore the wrapped model's streaming states.

Source code in src/resdag/core/model.py
1402
1403
1404
def set_state(self, states: Mapping[str, torch.Tensor], strict: bool = True) -> None:
    """Restore the wrapped model's streaming states."""
    self._model_api.set_state(states, strict=strict)

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 int builds a single reservoir; a sequence of int builds a stack (one reservoir per entry, in order). Required unless layers is given.

TYPE: int or sequence of int DEFAULT: None

feedback_size

Dimension of the feedback signal entering the first reservoir. Required unless layers is given. For stacked reservoirs only the first layer's feedback size is taken from this argument; the feedback size of each subsequent layer is the previous layer's reservoir size.

TYPE: int DEFAULT: None

input_size

Dimension of an optional driving input fed to the first reservoir. If None (default), the extractor operates in the feedback-only, single-positional-input mode required by torch.nn.Sequential.

TYPE: int DEFAULT: None

trainable

If True, the reservoir parameters require gradients (full BPTT through the recurrence). The default False freezes them, the standard reservoir-computing configuration.

TYPE: bool DEFAULT: False

layers

Pre-built reservoir layer(s) to wrap directly instead of constructing new ones. Any resdag.layers.reservoirs.BaseReservoirLayer subclass is accepted (ESNLayer, NGReservoirLayer, future reservoir types), not just ESNLayer. When given, reservoir_size / feedback_size / input_size must be omitted (the layers already define them), but trainable still applies as a freeze/unfreeze toggle over the provided layers. The layers are wrapped by reference — their parameters are shared, not copied.

TYPE: BaseReservoirLayer or sequence of BaseReservoirLayer DEFAULT: None

stateful

Carry reservoir states between forward calls. Use False for independent or shuffled minibatches: every call starts from zeros and leaves the wrapped layers' stored states untouched. Use forward_stateless when state must be passed explicitly.

TYPE: bool DEFAULT: True

**layer_kwargs

Extra keyword arguments forwarded to every ESNLayer that this constructor builds (for example spectral_radius, leak_rate, activation, topology, seed). Ignored when layers is provided.

TYPE: object DEFAULT: {}

ATTRIBUTE DESCRIPTION
reservoirs

The wrapped reservoir layer(s), in feed order.

TYPE: ModuleList

output_size

Feature dimension of the extractor's output (the last reservoir's reservoir_size).

TYPE: int

RAISES DESCRIPTION
ValueError

If neither layers nor (reservoir_size, feedback_size) is given, if both forms are mixed, or if layers is empty.

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
def __init__(
    self,
    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,
) -> None:
    super().__init__()

    if layers is not None:
        if reservoir_size is not None or feedback_size is not None or input_size is not None:
            raise ValueError(
                "Pass either pre-built `layers` or "
                "`reservoir_size`/`feedback_size`/`input_size`, not both."
            )
        if layer_kwargs:
            raise ValueError(
                "Extra layer keyword arguments are not supported when "
                "wrapping pre-built `layers`."
            )
        built = self._wrap_layers(layers)
    else:
        built = self._build_layers(
            reservoir_size=reservoir_size,
            feedback_size=feedback_size,
            input_size=input_size,
            **layer_kwargs,
        )

    self.reservoirs: nn.ModuleList = nn.ModuleList(built)
    self.stateful = stateful
    # Apply the freeze/unfreeze toggle uniformly over the wrapped layers.
    self.unfreeze() if trainable else self.freeze()

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 resdag.layers.reservoirs.BaseReservoirLayer submodules (typically an resdag.core.ESNModel). Reservoirs are collected in torch.nn.Module.named_modules order.

TYPE: Module

trainable

Freeze/unfreeze toggle applied to the shared reservoir layers after wrapping. Because the layers are shared, this also changes requires_grad on the source model's reservoir parameters.

TYPE: bool DEFAULT: False

stateful

Carry state between calls. False leaves the source model's stored states untouched and processes independent sequences.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
ReservoirFeatureExtractor

Extractor wrapping the model's reservoir layers by reference.

RAISES DESCRIPTION
ValueError

If esn_model contains no reservoir layers.

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
@classmethod
def from_model(
    cls,
    esn_model: nn.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.

    Parameters
    ----------
    esn_model : torch.nn.Module
        A model containing one or more
        `resdag.layers.reservoirs.BaseReservoirLayer` submodules
        (typically an `resdag.core.ESNModel`).  Reservoirs are
        collected in `torch.nn.Module.named_modules` order.
    trainable : bool, default=False
        Freeze/unfreeze toggle applied to the shared reservoir layers after
        wrapping.  Because the layers are shared, this also changes
        `requires_grad` on the source model's reservoir parameters.
    stateful : bool, default=True
        Carry state between calls. `False` leaves the source model's
        stored states untouched and processes independent sequences.

    Returns
    -------
    ReservoirFeatureExtractor
        Extractor wrapping the model's reservoir layers by reference.

    Raises
    ------
    ValueError
        If `esn_model` contains no reservoir layers.

    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
    """
    reservoirs = [
        module
        for _, module in esn_model.named_modules()
        if isinstance(module, BaseReservoirLayer)
    ]
    if not reservoirs:
        raise ValueError(
            "`esn_model` contains no reservoir layers (BaseReservoirLayer) "
            "to reuse. Build the extractor from sizes instead."
        )
    return cls(layers=reservoirs, trainable=trainable, stateful=stateful)

forward

forward(feedback: Tensor, *driving_inputs: Tensor) -> Tensor

Map a feedback sequence to reservoir features.

PARAMETER DESCRIPTION
feedback

Feedback signal of shape (batch, timesteps, feedback_size).

TYPE: Tensor

*driving_inputs

Optional driving input of shape (batch, timesteps, input_size), passed to the first reservoir only. At most one is supported.

TYPE: Tensor DEFAULT: ()

RETURNS DESCRIPTION
Tensor

Reservoir features of shape (batch, timesteps, output_size).

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
def forward(
    self,
    feedback: torch.Tensor,
    *driving_inputs: torch.Tensor,
) -> torch.Tensor:
    """
    Map a feedback sequence to reservoir features.

    Parameters
    ----------
    feedback : torch.Tensor
        Feedback signal of shape `(batch, timesteps, feedback_size)`.
    *driving_inputs : torch.Tensor
        Optional driving input of shape `(batch, timesteps, input_size)`,
        passed to the **first** reservoir only.  At most one is supported.

    Returns
    -------
    torch.Tensor
        Reservoir features of shape `(batch, timesteps, output_size)`.

    Raises
    ------
    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.
    """
    if len(driving_inputs) > 1:
        raise ValueError("Only one driving input tensor allowed")
    if not self.stateful:
        independent_features, _ = self.forward_stateless(feedback, *driving_inputs)
        return independent_features

    # The driving input enters the first reservoir; deeper reservoirs
    # consume the previous layer's features as their (sole) feedback.
    layers = self._layers
    features: torch.Tensor = layers[0](feedback, *driving_inputs)
    for reservoir in layers[1:]:
        features = reservoir(features)
    return features

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
def forward_stateless(
    self,
    feedback: torch.Tensor,
    *driving_inputs: torch.Tensor,
    states: Iterable[torch.Tensor] | None = None,
    compile: bool = False,
) -> tuple[torch.Tensor, tuple[torch.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.
    """
    if feedback.dim() != 3:
        raise ValueError(f"Feedback must be 3D (B, T, F), got shape {feedback.shape}")
    if len(driving_inputs) > 1:
        raise ValueError("Only one driving input tensor allowed")
    for driver in driving_inputs:
        if driver.dim() != 3 or driver.shape[:2] != feedback.shape[:2]:
            raise ValueError(
                "Driving input must be 3D and match feedback batch/time dimensions"
            )

    layers = self._layers
    initial = tuple(states) if states is not None else None
    if initial is not None and len(initial) != len(layers):
        raise ValueError(f"Expected {len(layers)} reservoir states, got {len(initial)}")

    features = feedback
    final: list[torch.Tensor] = []
    for i, layer in enumerate(layers):
        state = (
            layer.cell.init_state(features.shape[0], features.device, features.dtype)
            if initial is None
            else initial[i]
        )
        layer.cell.validate_state(state)
        if state.shape[0] != features.shape[0]:
            raise ValueError("State batch size must match feedback batch size")
        inputs = [features, *driving_inputs] if i == 0 else [features]
        features, state = layer.forward_stateless(inputs, state, compile=compile)
        final.append(state)
    return features, tuple(final)

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 None (default), states are set to None and lazily re-initialised on the next forward pass.

TYPE: int DEFAULT: None

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
def reset_state(self, batch_size: int | None = None) -> None:
    """
    Reset every wrapped reservoir's internal state.

    Parameters
    ----------
    batch_size : int, optional
        If given, materialise a zero state with this batch size on each
        reservoir's device/dtype.  If `None` (default), states are set to
        `None` and lazily re-initialised on the next forward pass.

    See Also
    --------
    on_epoch_start : Alias intended for use as an epoch-reset hook.
    """
    for reservoir in self._layers:
        reservoir.reset_state(batch_size=batch_size)

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 reset_state.

TYPE: int DEFAULT: None

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
def on_epoch_start(self, 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.

    Parameters
    ----------
    batch_size : int, optional
        Forwarded to `reset_state`.

    Examples
    --------
    >>> for epoch in range(num_epochs):  # doctest: +SKIP
    ...     extractor.on_epoch_start()
    ...     for batch in loader:
    ...         ...  # train the head
    """
    self.reset_state(batch_size=batch_size)

freeze

Freeze the reservoir: set requires_grad=False on all its parameters.

RETURNS DESCRIPTION
ReservoirFeatureExtractor

self, to allow chaining.

Source code in src/resdag/core/feature_extractor.py
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
def freeze(self) -> ReservoirFeatureExtractor:
    """
    Freeze the reservoir: set `requires_grad=False` on all its parameters.

    Returns
    -------
    ReservoirFeatureExtractor
        `self`, to allow chaining.
    """
    for reservoir in self._layers:
        if hasattr(reservoir.cell, "trainable"):
            setattr(reservoir.cell, "trainable", False)
        for param in reservoir.parameters():
            param.requires_grad_(False)
    return self

unfreeze

Unfreeze the reservoir: set requires_grad=True on all its parameters.

RETURNS DESCRIPTION
ReservoirFeatureExtractor

self, to allow chaining.

Source code in src/resdag/core/feature_extractor.py
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
def unfreeze(self) -> ReservoirFeatureExtractor:
    """
    Unfreeze the reservoir: set `requires_grad=True` on all its parameters.

    Returns
    -------
    ReservoirFeatureExtractor
        `self`, to allow chaining.
    """
    for reservoir in self._layers:
        if hasattr(reservoir.cell, "trainable"):
            setattr(reservoir.cell, "trainable", True)
        for param in reservoir.parameters():
            param.requires_grad_(True)
    return self

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: int

dtype

Tensor dtype. Defaults to torch.get_default_dtype().

TYPE: dtype DEFAULT: None

device

Device for the symbolic example, matching layers initialized there.

TYPE: device or str DEFAULT: None

RETURNS DESCRIPTION
SymbolicTensor

Placeholder input with shape (1, feature_size).

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
def reservoir_input(
    feature_size: int,
    dtype: torch.dtype | None = None,
    *,
    device: torch.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).

    Parameters
    ----------
    feature_size : int
        Number of features per timestep.
    dtype : torch.dtype, optional
        Tensor dtype. Defaults to `torch.get_default_dtype()`.
    device : torch.device or str, optional
        Device for the symbolic example, matching layers initialized there.

    Returns
    -------
    pytorch_symbolic.SymbolicTensor
        Placeholder input with shape `(1, feature_size)`.

    Examples
    --------
    >>> inp = reservoir_input(3)
    >>> inp.shape
    torch.Size([1, 1, 3])
    """
    if dtype is None:
        dtype = torch.get_default_dtype()
    if device is None:
        return ps.Input((1, feature_size), dtype=dtype)
    with torch.device(device):
        return ps.Input((1, feature_size), dtype=dtype)

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.

ReservoirStates module-attribute

ReservoirStates = dict[str, Tensor]