Skip to content

Reference

ESN preset

rd.ESN is a standard torch.nn.Module for a classic reservoir and readout. It uses the same training-only scaling, original units, state handling and forecast timing as Model.

import torch
import resdag as rd

series = torch.stack((torch.linspace(0, 8, 160).sin(),
                      torch.linspace(0, 8, 160).cos()), dim=-1)
esn = rd.ESN(reservoir_size=24, washout=10, seed=3).fit(series)
prediction = esn.forecast(horizon=20)  # Tensor, (20, 2), original units
raw_graph = esn.graph                # ESNModel, for already-normalized inputs

A 2-D input stays 2-D. A batched (batch, time, features) input keeps its batch axis even when batch=1. Ordinary esn(x) carries state and retains gradients; call esn.reset_state() between unrelated sequences. esn.forward_stateless(x) returns predictions and explicit recurrent states without changing stored state. prediction_lead sets the target's distance into the future. Its default feedback delay follows that lead; explicit connections use the preset's "input" and "output" ports. These controls and forecast(execution="history") use the same rules as the common model workflow.

Build before attaching an optimizer

Pass input_size to build eagerly, or call build(width) before collecting parameters. Otherwise the first successful fit infers the feature width.

pipeline_esn = rd.ESN(
    reservoir_size=16, input_size=2, washout=10, seed=4,
    readout_kwargs={"trainable": True},
).fit(series)
optimizer = torch.optim.Adam(pipeline_esn.parameters(), lr=1e-3)
pipeline_esn.reset_state()
batch = series[:8].detach().requires_grad_()
optimizer.zero_grad()
pipeline_esn(batch).square().mean().backward()
optimizer.step()
assert batch.grad is not None

The single registered esn.workflow child is a Model; .graph gives the raw symbolic graph. Refitting preserves the existing parameter objects. Use Model(inputs=..., outputs=...) for custom branches, drivers and multiple heads.

input_to_readout=True includes the current input alongside reservoir states in the readout features. Set it to False for a head using reservoir memory alone. The setting is a strict boolean and can be supplied before lazy building or with input_size for eager construction. Automatic vanilla tuning tries both values. A custom search_space replaces that search; an omitted setting keeps the current recipe's value. Saving preserves the selected wiring.

input_transforms={"input": module} and output_transforms={"output": module} override the preset's preprocessing per port. Supplied modules remain registered while the preset is lazy, and successful building/fitting keeps the original module and Parameter objects. A failed first fit leaves them registered without attaching an incomplete workflow. Build before collecting all model parameters for an optimizer. Custom modules use the reversible protocol described in custom preprocessing.

Placement, solvers and checkpoints

An untouched lazy preset adopts the first floating tensor's device and dtype. Explicit constructor settings and pre-build .to(...)/.double() conversions fix the current placement. Later refits require matching tensors, as ordinary PyTorch modules do. build(width, device=..., dtype=...) selects placement explicitly; use .to(...) to move an already-built preset.

The default readout="auto" checks numerical safety and chooses a solve while preserving the requested alpha. readout_kwargs configures it, for example {"solver": "svd"} or {"solve_dtype": torch.float32, "cpu_fallback": False}. Its last_solve report records the actual solver, working device/precision, conditioning and any fallback. Native MPS fits use supported float32 operations; an unsafe or unsupported solve warns before using CPU float64 unless fallback was disabled. Fitted parameters and predictions remain on the model device. See readout solvers for explicit alternatives and their own keyword settings. Reservoir options and custom initializers continue to pass through the preset.

A matching preset can restore a state_dict before its input width is built. Checkpoint metadata validates preset architecture settings before weight copies; scaling, observed history and trajectory sampling are restored by Model. Custom Python callables and initializer implementations must remain available with matching configuration. To save the full architecture and fitted state, use esn.save("model.pt") and rd.load("model.pt"); see save, load and diagrams. The current ESN and Model metadata version is 2. Older metadata is rejected; reconstruct and refit those models before saving a current checkpoint.

With the optional dynamics extra, fit(trajectory) and timestamped forecasts work exactly as in the trajectory guide. The named single-port spelling fit({"input": trajectory}) also works, with explicit trajectory targets under {"output": target} when needed. Ordinary calls always return Torch tensors; forecast(return_type="tensor") keeps trajectory-trained predictions on the model device.

See the ESN migration guide for the breaking API changes.

Method reference

fit returns this same module. forecast produces autonomous predictions; forward follows observed inputs with carried state. For differentiable chunking, forward_stateless returns a prediction and named states without changing the stored state. get_state, set_state and reset_state manage streaming explicitly. Standard inherited Torch methods and checkpoint protocol hooks remain available and are omitted from this reference.

facade

A standard PyTorch ESN preset using the common resdag.Model workflow.

ESN

ESN(
    reservoir_size: int = 500,
    *,
    input_size: int | None = None,
    spectral_radius: float = 0.9,
    leak_rate: float = 1.0,
    washout: int = 100,
    alpha: float = 1e-06,
    preprocessing: Preprocessing = "standard",
    input_transforms: Mapping[str, Module] | None = None,
    output_transforms: Mapping[str, Module] | None = None,
    prediction_lead: int | Mapping[str, int] = 1,
    feedback: Sequence[Feedback] | None = None,
    readout: ReadoutSpec = "auto",
    readout_kwargs: dict[str, Any] | None = None,
    topology: TopologySpec = None,
    feedback_initializer: InitializerSpec = None,
    activation: str = "tanh",
    bias: bool = True,
    readout_bias: bool = True,
    input_to_readout: bool = True,
    trainable: bool = False,
    seed: int | None = None,
    device: device | str | None = None,
    dtype: dtype | None = None,
    resample_dt: float | None = None,
    resample_method: Literal["linear", "pchip", "cubic"] = "linear",
    **reservoir_kwargs: Any
)

Bases: Module

A classic ESN preset with the same original-unit workflow as Model.

ESN(input_size=3) builds eagerly, making all parameters available before attaching an optimizer. Without input_size, fit infers the width and attaches a successfully fitted workflow. Call build explicitly when constructing a larger PyTorch pipeline before its first fit.

fit accepts floating Torch tensors or a TSDynamics trajectory. Ordinary forward returns Torch tensors, carries recurrent state, preserves layout and gradients, and uses fitted training-only scaling. forecast has the same keyword-only horizon and return conventions as Model.

The single registered workflow child is a Model; its raw symbolic graph is exposed by graph. Custom DAGs, drivers and multiple outputs use Model directly. readout/readout_kwargs expose solver choices; additional reservoir settings and custom initializers pass through to resdag.models.classic_esn. input_to_readout=True includes the raw input alongside reservoir states in the readout; False uses states alone. Automatic tuning of this preset compares both choices by default.

An untouched lazy preset adopts the first floating tensor's device/dtype. Explicit constructor placement or a pre-build to/double conversion fixes placement; later fitting follows ordinary Torch placement validation. build uses the current placement unless explicitly overridden. Checkpoints record width and preset configuration, allowing a matching unbuilt preset to load; arbitrary custom Python configurations must still be reconstructed.

Source code in src/resdag/facade.py
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
def __init__(
    self,
    reservoir_size: int = 500,
    *,
    input_size: int | None = None,
    spectral_radius: float = 0.9,
    leak_rate: float = 1.0,
    washout: int = 100,
    alpha: float = 1e-6,
    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,
    readout: ReadoutSpec = "auto",
    readout_kwargs: dict[str, Any] | None = None,
    topology: TopologySpec = None,
    feedback_initializer: InitializerSpec = None,
    activation: str = "tanh",
    bias: bool = True,
    readout_bias: bool = True,
    input_to_readout: bool = True,
    trainable: bool = False,
    seed: int | None = None,
    device: torch.device | str | None = None,
    dtype: torch.dtype | None = None,
    resample_dt: float | None = None,
    resample_method: Literal["linear", "pchip", "cubic"] = "linear",
    **reservoir_kwargs: Any,
) -> None:
    super().__init__()
    reservoir_size = _positive_width(reservoir_size, "reservoir_size")
    if type(input_to_readout) is not bool:
        raise TypeError("input_to_readout must be a bool")
    washout = _washout(washout)
    lead = prediction_leads(prediction_lead, ("output",))[0]
    connections = feedback_specs(feedback)
    resample_dt, validated_method = validate_resampling_options(resample_dt, resample_method)
    if preprocessing not in (
        None,
        "off",
        "standard",
        "minmax",
        "noncentered",
        "meanpreserving",
    ):
        raise ValueError("preprocessing must be a known normalization method, 'off', or None")
    reference = torch.empty(0, device=device, dtype=dtype)
    if not reference.is_floating_point():
        raise ValueError("dtype must be a real floating Torch dtype")
    reserved = {"feedback_size", "output_size", "readout_alpha"}.intersection(reservoir_kwargs)
    if reserved:
        raise ValueError(
            f"Preset dimensions/readout settings cannot be overridden: {sorted(reserved)}"
        )
    self.register_buffer("_reference", reference, persistent=False)
    self.add_module("workflow", None)
    self._input_size: int | None = None
    self._device_pinned, self._dtype_pinned = device is not None, dtype is not None
    overrides = []
    for mapping, name in ((input_transforms, "input"), (output_transforms, "output")):
        if mapping is not None and (not isinstance(mapping, Mapping) or set(mapping) - {name}):
            raise ValueError(
                f"ESN transform override keys must be declared port names: [{name!r}]"
            )
        overrides.append(dict(mapping or {}))
    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(nn.Identity(), originals)
    # Originals remain ordinary registered modules while the lazy graph is
    # absent. A staged first fit only transfers them after it succeeds.
    self._pending_input_transforms: nn.ModuleDict | None = (
        nn.ModuleDict(overrides[0]) if overrides[0] else None
    )
    self._pending_output_transforms: nn.ModuleDict | None = (
        nn.ModuleDict(overrides[1]) if overrides[1] else None
    )
    self._workflow_options: dict[str, Any] = {
        "washout": washout,
        "preprocessing": preprocessing,
        "prediction_lead": lead,
        "feedback": connections,
        "resample_dt": resample_dt,
        "resample_method": validated_method,
        "input_transforms": overrides[0] or None,
        "output_transforms": overrides[1] or None,
    }
    self._factory_options = {
        "reservoir_size": reservoir_size,
        "spectral_radius": spectral_radius,
        "leak_rate": leak_rate,
        "readout_alpha": alpha,
        "readout": readout,
        "readout_kwargs": dict(readout_kwargs or {}),
        "topology": topology,
        "feedback_initializer": feedback_initializer,
        "activation": activation,
        "bias": bias,
        "readout_bias": readout_bias,
        "input_to_readout": input_to_readout,
        "trainable": trainable,
        "seed": seed,
        **reservoir_kwargs,
    }
    # The default includes the input, including in previously saved preset
    # configurations. Only the states-only choice changes that architecture.
    architecture_options = dict(self._factory_options)
    if input_to_readout:
        architecture_options.pop("input_to_readout")
    self._architecture = (
        _configuration(architecture_options),
        tuple(
            tuple((name, transform_schema(module, 0)) for name, module in mapping.items())
            for mapping in overrides
        ),
    )
    if input_size is not None:
        self.build(input_size)

input_size property

input_size: int | None

Observed feature width, available after eager construction/build/fit.

is_built property

is_built: bool

Whether the input width is fixed and the workflow has been constructed.

is_fitted property

is_fitted: bool

Whether readout fitting and training-only preprocessing succeeded.

graph property

graph: ESNModel

The original raw symbolic graph; call build() or fit() before access.

washout property

washout: int

Number of initial observed rows excluded from readout fitting.

preprocessing property

preprocessing: str | None

Configured normalization method, or None when it is disabled.

prediction_leads property

prediction_leads: dict[str, int]

Prediction offsets by output name; the preset has one 'output' head.

feedback property

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

Explicit feedback routes, or None for automatic output-to-input routing.

save_formats property

save_formats: tuple[str, ...]

Supported complete-model checkpoint and diagram suffixes.

build

build(
    input_size: int, *, device: device | str | None = None, dtype: dtype | None = None
) -> ESN

Materialize parameters before attaching optimizers; same-width calls are idempotent.

Source code in src/resdag/facade.py
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
def build(
    self,
    input_size: int,
    *,
    device: torch.device | str | None = None,
    dtype: torch.dtype | None = None,
) -> ESN:
    """Materialize parameters before attaching optimizers; same-width calls are idempotent."""
    width = _positive_width(input_size, "input_size")
    placement = self._reference.device if device is None else torch.device(device)
    precision = self._reference.dtype if dtype is None else dtype
    if self.workflow is not None:
        reference = module_reference(self.graph)
        assert reference is not None
        if width != self.input_size:
            raise ValueError(
                "ESN input_size is fixed after build; construct a new preset for another width"
            )
        if (device is not None and placement != reference.device) or (
            dtype is not None and precision != reference.dtype
        ):
            raise ValueError("ESN is already built; use .to() to change its device/dtype")
        return self
    if not torch.empty(0, dtype=precision).is_floating_point():
        raise ValueError("dtype must be a real floating Torch dtype")
    with torch.inference_mode(False):
        candidate = self._new_workflow(width, placement, precision)
    self._attach(candidate, width)
    self._device_pinned = self._dtype_pinned = True
    return self

fit

fit(
    training: Streams | Trajectory | Mapping[str, Trajectory],
    targets: Streams | Trajectory | Mapping[str, Trajectory] | None = None,
) -> ESN

Fit with Model's train-only scaling, explicit targets and transactional refitting.

Source code in src/resdag/facade.py
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
def fit(
    self,
    training: Streams | Trajectory | Mapping[str, Trajectory],
    targets: Streams | Trajectory | Mapping[str, Trajectory] | None = None,
) -> ESN:
    """Fit with Model's train-only scaling, explicit targets and transactional refitting."""
    if self.workflow is not None:
        self.workflow.fit(training, targets)
        return self
    data: Any = training
    if isinstance(training, Mapping):
        if set(training) != {"input"}:
            raise ValueError("ESN training mapping must contain exactly the key 'input'")
        data = training["input"]
    if is_trajectory(data):
        data = torch.as_tensor(cast(Any, data).y)
    if not isinstance(data, torch.Tensor):
        raise TypeError(
            "ESN training requires a floating torch.Tensor or a TSDynamics trajectory"
        )
    if data.ndim not in (2, 3):
        raise ValueError("ESN training requires 2-D or 3-D time-series tensors")
    if not data.is_floating_point():
        raise TypeError("ESN training requires a real floating tensor")
    width = _positive_width(data.shape[-1], "input_size")
    placement = self._reference.device if self._device_pinned else data.device
    precision = self._reference.dtype if self._dtype_pinned else data.dtype
    with torch.inference_mode(False):
        candidate = self._new_workflow(width, placement, precision)
    candidate.fit(training, targets)
    self._attach(candidate, width)
    self._device_pinned = self._dtype_pinned = True
    return self

save

save(path: str | Path, **options: Any) -> Any

Save this complete preset or a DAG diagram, selected by suffix.

Source code in src/resdag/facade.py
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
def save(self, path: str | Path, **options: Any) -> Any:
    """Save this complete preset or a DAG diagram, selected by suffix."""
    workflow = self._require_workflow()
    suffix = Path(path).suffix.lower().lstrip(".")
    requested_format = options.get("format")
    if requested_format is not None and not isinstance(requested_format, str):
        raise TypeError("format must be a string or None")
    selected = requested_format.lower() if requested_format else suffix or "pt"
    if selected not in ("pt", "pth"):
        return workflow.save(path, **options)
    from resdag.artifacts import save_model

    format = options.pop("format", None)
    if format is not None and format.lower() not in ("pt", "pth"):
        raise ValueError("Model checkpoint format must be pt or pth")
    if suffix and suffix != selected:
        raise ValueError("Save format and suffix must agree")
    destination = Path(path) if suffix else Path(path).with_suffix(f".{selected}")
    return save_model(self, destination, **options)

plot_model

plot_model(**options: Any) -> Any

Display or export the preset DAG without running it.

Source code in src/resdag/facade.py
457
458
459
def plot_model(self, **options: Any) -> Any:
    """Display or export the preset DAG without running it."""
    return self._require_workflow().plot_model(**options)

tune

tune(
    training: Streams | Trajectory | Mapping[str, Trajectory],
    targets: Streams | Trajectory | Mapping[str, Trajectory] | None = None,
    *,
    preset: Literal["quick", "balanced", "thorough"] = "balanced",
    n_trials: int | None = None,
    horizon: int | None = None,
    n_jobs: int = 1,
    **options: Any
) -> ESN

Tune preset settings, refit the winner and return this same ESN.

Requires resdag[hpo]. Presets automatically rebuild reservoir sizes, initializations and readouts together. search_space(trial) overrides the default Optuna search. See the tuning guide for explicit validation, seeds, objectives, study storage and tuning_report. Failed tuning preserves the current model. Create optimizers afterward.

Source code in src/resdag/facade.py
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
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,
) -> ESN:
    """Tune preset settings, refit the winner and return this same ESN.

    Requires `resdag[hpo]`. Presets automatically rebuild reservoir
    sizes, initializations and readouts together. `search_space(trial)`
    overrides the default Optuna search. See the tuning guide for explicit
    validation, seeds, objectives, study storage and `tuning_report`.
    Failed tuning preserves the current model. Create optimizers afterward.
    """
    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

forward

forward(inputs: Streams) -> Tensor

Predict original units with carried state and ordinary Torch autograd/hooks.

Source code in src/resdag/facade.py
497
498
499
def forward(self, inputs: Streams) -> torch.Tensor:
    """Predict original units with carried state and ordinary Torch autograd/hooks."""
    return cast(torch.Tensor, self._require_workflow()(inputs))

forward_stateless

forward_stateless(
    inputs: Streams,
    *,
    states: Mapping[str, Tensor] | None = None,
    compile: bool = False
) -> tuple[Tensor, ReservoirStates]

Predict original-unit signals with explicitly returned recurrent state.

Inputs preserve the (time, features) or (batch, time, features) layout used by forward. Omitting states starts from each reservoir's configured reset state; otherwise provide the complete mapping returned by an earlier call. The output and returned states retain gradients across chunks. Stored recurrent state is unchanged. Other modules retain their normal training-mode and hook behavior.

compile=True requests the existing supported compiled scan; its device/capability checks and eager fallback follow Model.

Source code in src/resdag/facade.py
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
def forward_stateless(
    self,
    inputs: Streams,
    *,
    states: Mapping[str, torch.Tensor] | None = None,
    compile: bool = False,
) -> tuple[torch.Tensor, ReservoirStates]:
    """Predict original-unit signals with explicitly returned recurrent state.

    Inputs preserve the `(time, features)` or `(batch, time, features)`
    layout used by `forward`. Omitting `states` starts from each
    reservoir's configured reset state; otherwise provide the complete
    mapping returned by an earlier call. The output and returned states
    retain gradients across chunks. Stored recurrent state is unchanged.
    Other modules retain their normal training-mode and hook behavior.

    `compile=True` requests the existing supported compiled scan; its
    device/capability checks and eager fallback follow `Model`.
    """
    from resdag.core._hooks import call_with_states, has_execution_hooks, state_paths

    if has_execution_hooks(self):
        workflow = self._require_workflow()
        workflow._backend.validate_stateless(workflow.graph)
        return cast(
            tuple[torch.Tensor, ReservoirStates],
            call_with_states(
                self, (inputs,), states, state_paths(self, "workflow.graph."), compile=compile
            ),
        )
    output, final = self._require_workflow().forward_stateless(
        inputs, states=states, compile=compile
    )
    return cast(torch.Tensor, output), final

forecast

forecast(
    history: Streams | Trajectory | Mapping[str, Trajectory] | None = None,
    *,
    horizon: int,
    future_inputs: Streams | Trajectory | Mapping[str, Trajectory] | None = None,
    return_warmup: bool = False,
    compile: bool = False,
    execution: Literal["fast", "history"] = "fast",
    return_type: Literal["auto", "tensor", "trajectory"] = "auto"
) -> Tensor | Trajectory

Forecast horizon future samples in the original signal units.

history resynchronizes recurrence on an observed prefix; omit it to use the fitted training tail. The first prediction follows its last observed sample. Every call resets recurrence and temporarily disables training noise. future_inputs supplies any declared non-feedback drivers; the ordinary one-input preset needs none.

return_warmup=True prepends the readout's predictions during history replay. execution='fast' uses framewise execution; 'history' supports causal temporal transforms by replaying growing prefixes. compile=True requests supported compiled forecasting. See Model.forecast for capability checks and fallback behavior.

Tensor inputs retain their two- or three-dimensional layout. return_type='auto' returns a TSDynamics trajectory after trajectory fitting or with trajectory history; 'tensor' keeps Torch output on the model device. A selected trajectory result requires a known clock.

Source code in src/resdag/facade.py
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
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",
) -> torch.Tensor | Trajectory:
    """Forecast `horizon` future samples in the original signal units.

    `history` resynchronizes recurrence on an observed prefix; omit it
    to use the fitted training tail. The first prediction follows its last
    observed sample. Every call resets recurrence and temporarily disables
    training noise. `future_inputs` supplies any declared non-feedback
    drivers; the ordinary one-input preset needs none.

    `return_warmup=True` prepends the readout's predictions during history
    replay. `execution='fast'` uses framewise execution; `'history'`
    supports causal temporal transforms by replaying growing prefixes.
    `compile=True` requests supported compiled forecasting. See
    `Model.forecast` for capability checks and fallback behavior.

    Tensor inputs retain their two- or three-dimensional layout.
    `return_type='auto'` returns a TSDynamics trajectory after trajectory
    fitting or with trajectory history; `'tensor'` keeps Torch output on
    the model device. A selected trajectory result requires a known clock.
    """
    from resdag.core._hooks import forecast_as

    with forecast_as(self):
        return cast(
            "torch.Tensor | Trajectory",
            self._require_workflow().forecast(
                history,
                horizon=horizon,
                future_inputs=future_inputs,
                return_warmup=return_warmup,
                compile=compile,
                return_type=return_type,
                execution=execution,
            ),
        )

reset_state

reset_state() -> None

Clear carried recurrent state; the next call uses configured reset values.

Source code in src/resdag/facade.py
582
583
584
def reset_state(self) -> None:
    """Clear carried recurrent state; the next call uses configured reset values."""
    self._require_workflow().reset_state()

get_state

get_state() -> ReservoirStates

Return copies of initialized recurrent states, keyed as in forward_stateless.

Source code in src/resdag/facade.py
586
587
588
def get_state(self) -> ReservoirStates:
    """Return copies of initialized recurrent states, keyed as in `forward_stateless`."""
    return self._require_workflow().get_state()

set_state

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

Restore named recurrent states using Model.set_state validation.

strict=True requires the model's complete state-key set. Restored states are copied and matched to each reservoir's device and dtype.

Source code in src/resdag/facade.py
590
591
592
593
594
595
596
def set_state(self, states: Mapping[str, torch.Tensor], strict: bool = True) -> None:
    """Restore named recurrent states using `Model.set_state` validation.

    `strict=True` requires the model's complete state-key set. Restored
    states are copied and matched to each reservoir's device and dtype.
    """
    self._require_workflow().set_state(states, strict=strict)