Skip to content

Reference

Utilities

Use rd.SeedStreams(master_seed)["branch_name"] for stable, independent initialization seeds. Adding or reordering named branches leaves their existing seeds unchanged. See the public component recipes.

Use data and datasets for file I/O, preparation, streaming windows and benchmark generators. Existing convenience imports from resdag.utils and resdag.utils.data resolve to the same canonical functions.

The ESP index, esp_index, is re-exported at resdag.utils and at the top level, so all three of these work:

from resdag import esp_index
from resdag.utils import esp_index
from resdag.utils.states import esp_index  # canonical home

utils

Utility Functions

This module provides utility functions for data loading, preparation, and general operations in resdag.

Submodules

data Data loading and preparation utilities for ESN training. states Reservoir-state diagnostics (the Echo State Property index).

FUNCTION DESCRIPTION
seed_everything

Seed Python, NumPy, and torch (CPU + CUDA) for reproducible runs.

resolve_device

Resolve a device spec ('auto'/str/torch.device) to a torch.device.

create_rng

Create a NumPy random number generator with optional seed.

create_torch_generator

Create a torch Generator for reproducible weight/bias draws.

coerce_seed_to_int

Reduce an int/torch.Generator/None seed to a plain int (or None).

SeedStreams

Derive stable seeds for explicitly named model components.

SeedLike

Type alias for accepted seed inputs (int | torch.Generator | None).

DeviceLike

Type alias for accepted device specs (str | torch.device | None).

load_file

Load a time series from disk (re-exported from resdag.data).

prepare_esn_data

Split a series into ESN train/forecast segments (re-exported from resdag.data).

normalize_data

Normalize a series and return the fitted statistics (re-exported from resdag.data).

denormalize_data

Invert a normalization back to the original scale (re-exported from resdag.data).

lorenz, rossler, henon, mackey_glass, narma, sine

Canonical reservoir-computing dataset generators (re-exported from resdag.datasets).

esp_index

Echo State Property index — the library's signature stability diagnostic (re-exported from resdag.utils.states).

Examples:

>>> import resdag as rd
>>> data = rd.utils.load_file("timeseries.csv")
>>> warmup, train, target, f_warmup, val = rd.utils.prepare_esn_data(
...     data, warmup_steps=100, train_steps=500, val_steps=200
... )
>>> series = rd.utils.lorenz(2000)  # (1, 2000, 3) chaotic benchmark series
>>> from resdag.utils import esp_index  # signature stability diagnostic
See Also

resdag.utils.data : Data loading and preparation. resdag.utils.states : Echo State Property diagnostics.

DeviceLike module-attribute

DeviceLike = str | device | None

SeedLike module-attribute

SeedLike = int | Generator | None

SeedStreams dataclass

SeedStreams(master_seed: int)

Derive repeatable integer seeds without consuming any random stream.

Explicit names keep existing branches unchanged when another branch is added or construction order changes. Reusing a name intentionally gives the same seed; it does not share parameter tensors or recurrent state. Names are exact UTF-8 strings and are independent of Python's hash seed.

The blake2b-v1 algorithm is fixed: BLAKE2b with an eight-byte digest, personalization b"ResDAG.seed.v1", decimal master seed, a NUL separator and the UTF-8 name, masked to an unsigned 63-bit integer. These seeds work with Torch generators and NumPy's default_rng. This utility does not enable deterministic accelerator kernels or capture stochastic execution state; it controls initialization seeds only.

Examples:

>>> streams = SeedStreams(42)
>>> streams["fast"] == streams.seed_for("fast")
True
>>> streams["slow"] != streams["fast"]
True

seed_for

seed_for(name: str) -> int

Return the stable seed for a nonblank, explicitly named component.

Source code in src/resdag/utils/seeds.py
46
47
48
49
50
51
52
53
54
def seed_for(self, name: str) -> int:
    """Return the stable seed for a nonblank, explicitly named component."""
    if not isinstance(name, str):
        raise TypeError("SeedStreams component name must be a string")
    if not name.strip():
        raise ValueError("SeedStreams component name must not be blank")
    payload = str(self.master_seed).encode("ascii") + b"\0" + name.encode("utf-8")
    digest = hashlib.blake2b(payload, digest_size=8, person=b"ResDAG.seed.v1").digest()
    return int.from_bytes(digest, "big") & ((1 << 63) - 1)

create_rng

create_rng(seed: int | Generator | None = None) -> Generator

Create a NumPy random number generator.

This is the NumPy-RNG-for-graph-topology helper: it is threaded into the graph builders and named initializers, which draw exclusively from NumPy. For whole-program reproducibility (torch + NumPy + random at once) use seed_everything instead; for a torch torch.Generator for weight/bias draws use create_torch_generator.

PARAMETER DESCRIPTION
seed

If int, used as seed for a new Generator. If Generator, returned as-is. If None, the seed is derived from torch's global RNG so that torch.manual_seed propagates to the generator. This keeps graph-based topologies (which draw from NumPy) reproducible under the same torch global seed, matching the behaviour of matrix topologies that draw from torch directly.

TYPE: int, np.random.Generator, or None DEFAULT: None

RETURNS DESCRIPTION
Generator

A NumPy random number generator.

Notes

When seed is None the numpy seed is sampled from torch's global RNG via torch.randint. This advances the torch global RNG state, but ties every NumPy draw to torch.manual_seed for end-to-end reproducibility.

See Also

seed_everything : Seed torch, NumPy, and random in one call. create_torch_generator : Build a torch Generator for weight draws.

Source code in src/resdag/utils/general.py
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
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
def create_rng(seed: int | np.random.Generator | None = None) -> np.random.Generator:
    """Create a NumPy random number generator.

    This is the NumPy-RNG-for-graph-topology helper: it is threaded into the
    graph builders and named initializers, which draw exclusively from NumPy.
    For whole-program reproducibility (torch + NumPy + `random` at once) use
    `seed_everything` instead; for a torch `torch.Generator` for
    weight/bias draws use `create_torch_generator`.

    Parameters
    ----------
    seed : int, np.random.Generator, or None
        If int, used as seed for a new Generator.
        If Generator, returned as-is.
        If None, the seed is derived from torch's global RNG so that
        `torch.manual_seed` propagates to the generator. This keeps
        graph-based topologies (which draw from NumPy) reproducible under
        the same torch global seed, matching the behaviour of matrix
        topologies that draw from torch directly.

    Returns
    -------
    np.random.Generator
        A NumPy random number generator.

    Notes
    -----
    When `seed is None` the numpy seed is sampled from torch's global RNG
    via `torch.randint`. This advances the torch global RNG state, but ties
    every NumPy draw to `torch.manual_seed` for end-to-end reproducibility.

    See Also
    --------
    seed_everything : Seed torch, NumPy, and `random` in one call.
    create_torch_generator : Build a torch `Generator` for weight draws.
    """
    if isinstance(seed, np.random.Generator):
        return seed
    if seed is None:
        # Derive the numpy seed from torch's global RNG so that
        # torch.manual_seed(...) makes graph generators reproducible.
        seed = int(torch.randint(0, 2**63 - 1, (1,)).item())
    return np.random.default_rng(seed)

create_torch_generator

create_torch_generator(
    seed: SeedLike = None, device: device | str | None = None
) -> Generator

Create a torch torch.Generator for reproducible weight draws.

Used for the default nn.init weight/bias draws inside reservoir cells so that a single seed deterministically fixes every parameter without touching (and without depending on the prior state of) torch's global RNG.

PARAMETER DESCRIPTION
seed

If int, seeds a fresh generator on device. If torch.Generator, it is returned as-is (the caller's generator is threaded straight through, so successive draws advance one stream). If None, the generator is seeded from torch's global RNG so that torch.manual_seed still propagates — matching create_rng.

TYPE: int, torch.Generator, or None DEFAULT: None

device

Device for the new generator. Ignored when seed is already a torch.Generator.

TYPE: torch.device, str, or None DEFAULT: None

RETURNS DESCRIPTION
Generator

A generator suitable for passing to nn.init.* via generator=.

Notes

When seed is None the integer seed is sampled from torch's global RNG via torch.randint, advancing the global state but tying the draws to torch.manual_seed for end-to-end reproducibility.

Source code in src/resdag/utils/general.py
 63
 64
 65
 66
 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
def create_torch_generator(
    seed: SeedLike = None,
    device: torch.device | str | None = None,
) -> torch.Generator:
    """Create a torch `torch.Generator` for reproducible weight draws.

    Used for the default `nn.init` weight/bias draws inside reservoir cells so
    that a single `seed` deterministically fixes every parameter without
    touching (and without depending on the prior state of) torch's global RNG.

    Parameters
    ----------
    seed : int, torch.Generator, or None
        If `int`, seeds a fresh generator on `device`.
        If `torch.Generator`, it is returned as-is (the caller's generator is
        threaded straight through, so successive draws advance one stream).
        If `None`, the generator is seeded from torch's global RNG so that
        `torch.manual_seed` still propagates — matching `create_rng`.

    device : torch.device, str, or None
        Device for the new generator.  Ignored when `seed` is already a
        `torch.Generator`.

    Returns
    -------
    torch.Generator
        A generator suitable for passing to `nn.init.*` via `generator=`.

    Notes
    -----
    When `seed is None` the integer seed is sampled from torch's global RNG
    via `torch.randint`, advancing the global state but tying the draws to
    `torch.manual_seed` for end-to-end reproducibility.
    """
    if isinstance(seed, torch.Generator):
        return seed
    generator = torch.Generator(device=device if device is not None else "cpu")
    if seed is None:
        seed = int(torch.randint(0, 2**63 - 1, (1,)).item())
    generator.manual_seed(int(seed))
    return generator

coerce_seed_to_int

coerce_seed_to_int(seed: SeedLike) -> int | None

Reduce a torch/int/None seed to a plain int seed (or None).

The NumPy-backed graph builders and named initializers thread an integer (or None) seed down to create_rng. A torch.Generator cannot be passed there directly, so this helper extracts a deterministic integer from its initial seed — two generators created with the same manual_seed therefore yield the same int, keeping the topology a pure function of the generator.

PARAMETER DESCRIPTION
seed

Seed in any of the accepted forms.

TYPE: int, torch.Generator, or None

RETURNS DESCRIPTION
int or None

seed itself if it was an int; the generator's initial_seed() if it was a torch.Generator; None if it was None.

Source code in src/resdag/utils/general.py
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
def coerce_seed_to_int(seed: SeedLike) -> int | None:
    """Reduce a torch/int/None seed to a plain `int` seed (or `None`).

    The NumPy-backed graph builders and named initializers thread an integer
    (or `None`) seed down to `create_rng`.  A `torch.Generator`
    cannot be passed there directly, so this helper extracts a deterministic
    integer from its initial seed — two generators created with the same
    `manual_seed` therefore yield the same int, keeping the topology a pure
    function of the generator.

    Parameters
    ----------
    seed : int, torch.Generator, or None
        Seed in any of the accepted forms.

    Returns
    -------
    int or None
        `seed` itself if it was an `int`; the generator's
        `initial_seed()` if it was a `torch.Generator`; `None` if it
        was `None`.
    """
    if seed is None or isinstance(seed, int):
        return seed
    if isinstance(seed, torch.Generator):
        # initial_seed() is the value the generator was seeded with; identical
        # generators (same manual_seed) therefore map to the same int.
        return int(seed.initial_seed())
    raise TypeError(
        f"Invalid seed type: {type(seed).__name__}. Expected int, torch.Generator, or None."
    )

seed_everything

seed_everything(seed: int = 42, *, deterministic: bool = False) -> int

Seed Python, NumPy, and torch (CPU + CUDA) for reproducible runs.

Seeds every global RNG resdag and its dependencies draw from in one call: the random module, NumPy's legacy global RNG, torch's CPU RNG, and (when available) every visible CUDA device. The seed is returned so callers can log or thread it (e.g. an HPO loop deriving a per-trial seed).

PARAMETER DESCRIPTION
seed

Seed applied to every RNG.

TYPE: int DEFAULT: 42

deterministic

If True, also request deterministic algorithms from torch by enabling torch.use_deterministic_algorithms and disabling the cuDNN benchmark autotuner. This favours reproducibility over speed and may raise at runtime if a non-deterministic op has no deterministic implementation, so it is opt-in.

TYPE: (bool, keyword - only) DEFAULT: False

RETURNS DESCRIPTION
int

The seed that was applied, for logging or downstream threading.

Notes

This seeds the global RNGs. For local, side-effect-free reproducibility, prefer the generator factories: create_rng (NumPy, for graph topologies) and create_torch_generator (torch, for weight draws).

Examples:

>>> from resdag.utils import seed_everything
>>> seed_everything(0)
0
>>> import torch
>>> seed_everything(0); a = torch.randn(3)
0
>>> seed_everything(0); b = torch.randn(3)
0
>>> bool(torch.equal(a, b))
True
See Also

create_rng : NumPy generator for graph topologies (local RNG). create_torch_generator : torch generator for weight draws (local RNG). resolve_device : Resolve a device spec to a torch.device.

Source code in src/resdag/utils/general.py
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
def seed_everything(seed: int = 42, *, deterministic: bool = False) -> int:
    """Seed Python, NumPy, and torch (CPU + CUDA) for reproducible runs.

    Seeds every global RNG resdag and its dependencies draw from in one call:
    the `random` module, NumPy's legacy global RNG, torch's CPU RNG, and
    (when available) every visible CUDA device. The seed is returned so callers
    can log or thread it (e.g. an HPO loop deriving a per-trial seed).

    Parameters
    ----------
    seed : int, default 42
        Seed applied to every RNG.
    deterministic : bool, keyword-only, default False
        If `True`, also request deterministic algorithms from torch by
        enabling `torch.use_deterministic_algorithms` and disabling the
        cuDNN benchmark autotuner. This favours reproducibility over speed and
        may raise at runtime if a non-deterministic op has no deterministic
        implementation, so it is opt-in.

    Returns
    -------
    int
        The `seed` that was applied, for logging or downstream threading.

    Notes
    -----
    This seeds the *global* RNGs. For local, side-effect-free reproducibility,
    prefer the generator factories: `create_rng` (NumPy, for graph
    topologies) and `create_torch_generator` (torch, for weight draws).

    Examples
    --------
    >>> from resdag.utils import seed_everything
    >>> seed_everything(0)
    0
    >>> import torch
    >>> seed_everything(0); a = torch.randn(3)
    0
    >>> seed_everything(0); b = torch.randn(3)
    0
    >>> bool(torch.equal(a, b))
    True

    See Also
    --------
    create_rng : NumPy generator for graph topologies (local RNG).
    create_torch_generator : torch generator for weight draws (local RNG).
    resolve_device : Resolve a device spec to a `torch.device`.
    """
    random.seed(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)
    if torch.cuda.is_available():
        torch.cuda.manual_seed_all(seed)
    if deterministic:
        torch.use_deterministic_algorithms(True)
        torch.backends.cudnn.benchmark = False
        torch.backends.cudnn.deterministic = True
    return seed

resolve_device

resolve_device(spec: DeviceLike = 'auto') -> device

Resolve a device spec to a concrete torch.device.

Provides the 'auto' convenience used by HPO, examples, and reproducible experiments: it picks the best available backend (CUDA, then MPS, then CPU). Explicit specs pass through, with a CPU fallback if the requested accelerator is unavailable.

PARAMETER DESCRIPTION
spec

'auto' (or None) selects cuda → mps → cpu by availability. A torch.device is returned unchanged. An explicit string ('cpu', 'cuda', 'cuda:1', 'mps', …) is parsed into a torch.device; if it names an unavailable accelerator the result falls back to cpu.

TYPE: str, torch.device, or None DEFAULT: `'auto'`

RETURNS DESCRIPTION
device

The resolved device.

RAISES DESCRIPTION
TypeError

If spec is not a str, torch.device, or None.

Examples:

>>> from resdag.utils import resolve_device
>>> resolve_device("cpu")
device(type='cpu')
>>> resolve_device("auto").type in {"cuda", "mps", "cpu"}
True
See Also

seed_everything : Seed torch, NumPy, and random in one call.

Source code in src/resdag/utils/general.py
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
def resolve_device(spec: DeviceLike = "auto") -> torch.device:
    """Resolve a device spec to a concrete `torch.device`.

    Provides the `'auto'` convenience used by HPO, examples, and reproducible
    experiments: it picks the best available backend (CUDA, then MPS, then CPU).
    Explicit specs pass through, with a CPU fallback if the requested
    accelerator is unavailable.

    Parameters
    ----------
    spec : str, torch.device, or None, default `'auto'`
        `'auto'` (or `None`) selects `cuda` → `mps` → `cpu` by
        availability. A `torch.device` is returned unchanged. An explicit
        string (`'cpu'`, `'cuda'`, `'cuda:1'`, `'mps'`, …) is parsed into
        a `torch.device`; if it names an unavailable accelerator the
        result falls back to `cpu`.

    Returns
    -------
    torch.device
        The resolved device.

    Raises
    ------
    TypeError
        If `spec` is not a `str`, `torch.device`, or `None`.

    Examples
    --------
    >>> from resdag.utils import resolve_device
    >>> resolve_device("cpu")
    device(type='cpu')
    >>> resolve_device("auto").type in {"cuda", "mps", "cpu"}
    True

    See Also
    --------
    seed_everything : Seed torch, NumPy, and `random` in one call.
    """
    if isinstance(spec, torch.device):
        return spec
    if spec is None or spec == "auto":
        if torch.cuda.is_available():
            return torch.device("cuda")
        if torch.backends.mps.is_available():
            return torch.device("mps")
        return torch.device("cpu")
    if not isinstance(spec, str):
        raise TypeError(
            f"Invalid device spec: {type(spec).__name__}. Expected str, torch.device, or None."
        )
    device = torch.device(spec)
    if device.type == "cuda" and not torch.cuda.is_available():
        return torch.device("cpu")
    if device.type == "mps" and not torch.backends.mps.is_available():
        return torch.device("cpu")
    return device

states

State management and analysis utilities for reservoir layers.

esp_index

esp_index(
    model: "ESNModel",
    feedback_seq: Tensor,
    *driving_seqs: Tensor,
    history: bool = False,
    iterations: int = 10,
    transient: int = 0,
    window: int | None = None,
    relative: bool = False,
    chunk_size: int | None = None,
    verbose: bool = True
) -> Union[
    dict[str, list[Tensor]], Tuple[dict[str, list[Tensor]], dict[str, list[Tensor]]]
]

Compute the Echo State Property (ESP) index for reservoir layers.

The ESP index measures how quickly trajectories from different initial states converge when driven by the same input. All resdag.layers.reservoirs.base_reservoir.BaseReservoirLayer reservoirs are discovered automatically, so the diagnostic applies equally to ESN, NG-RC, and any future custom-cell reservoir.

Random restarts are drawn through each reservoir's public resdag.layers.reservoirs.base_reservoir.BaseReservoirLayer.set_random_state, which samples a standard-normal state — the same convention as resdag.core.ESNModel.set_random_reservoir_states. The index is therefore directly comparable to states produced elsewhere in the library.

PARAMETER DESCRIPTION
model

Model containing reservoir layers.

TYPE: ESNModel

feedback_seq

Feedback sequence, shape (batch, timesteps, features).

TYPE: Tensor

*driving_seqs

Optional driving sequences in model input order.

TYPE: Tensor DEFAULT: ()

history

If True, return full distance history over time.

TYPE: bool DEFAULT: False

iterations

Number of random initial states to average over.

TYPE: int DEFAULT: 10

transient

Timesteps to discard from sequence start.

TYPE: int DEFAULT: 0

window

Length of the trailing window over which the index is averaged. By default (None) the index is the mean over every post-transient timestep, which for a healthy reservoir is dominated by the early convergence transient rather than the asymptotic distance. Setting window=k averages only the last k post-transient steps, so the index reflects the asymptotic regime — a far more diagnostic statistic. Must be a positive integer no larger than the number of post-transient timesteps. Does not affect the returned history tensors, which always span the full post-transient sequence.

TYPE: int or None DEFAULT: None

relative

If True, normalise each per-step distance by the corresponding base-state norm, ||base - rand|| / (||base|| + eps), yielding a scale-free relative distance that is comparable across reservoir sizes and spectral radii. If False (default), the raw absolute distance is used. The normalisation is applied to both the returned index and the history tensors.

TYPE: bool DEFAULT: False

chunk_size

Maximum number of random restarts run together in a single batched forward pass. All restarts are statistically independent and differ only in their initial state, so they are folded into the batch dimension and evaluated in one forward pass instead of iterations sequential passes (typically a ~3x speed-up). A large reservoir_size * iterations product can exhaust device memory, however; set chunk_size to cap the per-pass batch at batch * chunk_size and process the restarts in chunks. None (default) runs all iterations restarts in one pass, transparently falling back to chunking (halving the chunk each time) if a CUDA out-of-memory error is raised.

TYPE: int or None DEFAULT: None

verbose

Print progress and skip messages.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
dict or tuple

If history=False: dict mapping layer names to single-element lists containing the ESP index scalar tensor. If history=True: tuple of (ESP indices dict, history dict). History tensors have shape (iterations, timesteps, batch) and span the full post-transient sequence regardless of window.

Reservoirs whose ESP is undefined (no randomisable state) are omitted from both dictionaries.

RAISES DESCRIPTION
ValueError

If transient is not smaller than the number of timesteps, if window is not a positive integer no larger than the number of post-transient timesteps, if the model contains no reservoir layers, or if no reservoir has a well-defined ESP.

Notes

For LINEAR systems (identity activation), input does NOT affect ESP because the input contribution cancels out in the state difference. This is mathematically correct behavior.

State is never mutated by direct assignment. The zero base orbit is set via res.reset_state(batch_size=...) and the random restarts via res.set_random_state(), so each cell's own shape contract (2-D for ESN, 3-D delay buffer for NG-RC) is honoured and validated by the public state-management API.

The caller's reservoir states are saved before the computation and restored afterwards (even on error), so calling esp_index never leaves the model's reservoirs in a mutated (random) state.

Batched restarts. The iterations random restarts are statistically independent and differ only in their initial state, so they are folded into the batch dimension: the feedback (and any drivers) are tiled iterations times, one random initial state is composed per restart into a single (batch * iterations, ...) state, and the whole ensemble is evaluated in one forward pass rather than iterations sequential passes. The random restarts are drawn in exactly the same order as the sequential loop (outer over restarts, inner over reservoirs), so the initial states are bit-identical to the sequential computation. The reservoir outputs — and hence the returned index — match the sequential value to floating-point rounding (typically < 1e-6 relative), the only difference being the reassociation of a wider batched matmul; the result is fully deterministic under a fixed seed. (If a reservoir cell injects per-step state noise in training mode, noise > 0, the batched noise draws differ from the sequential ones; the index remains a valid, seed-deterministic stochastic diagnostic but is no longer numerically identical. Run the model in eval mode to disable noise entirely.)

Examples:

Score only the asymptotic regime with a scale-free statistic:

idx = esp_index(model, feedback, window=50, relative=True)
See Also

resdag.core.ESNModel.set_random_reservoir_states : Source of the standard-normal restart convention used here.

Source code in src/resdag/utils/states/esp_index.py
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
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
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
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
325
326
327
328
329
330
331
332
333
334
335
336
def esp_index(
    model: "ESNModel",
    feedback_seq: torch.Tensor,
    *driving_seqs: torch.Tensor,
    history: bool = False,
    iterations: int = 10,
    transient: int = 0,
    window: int | None = None,
    relative: bool = False,
    chunk_size: int | None = None,
    verbose: bool = True,
) -> Union[
    dict[str, list[torch.Tensor]],
    Tuple[dict[str, list[torch.Tensor]], dict[str, list[torch.Tensor]]],
]:
    """
    Compute the Echo State Property (ESP) index for reservoir layers.

    The ESP index measures how quickly trajectories from different initial
    states converge when driven by the same input.  All
    `resdag.layers.reservoirs.base_reservoir.BaseReservoirLayer`
    reservoirs are discovered automatically, so the diagnostic applies equally
    to ESN, NG-RC, and any future custom-cell reservoir.

    Random restarts are drawn through each reservoir's public
    `resdag.layers.reservoirs.base_reservoir.BaseReservoirLayer.set_random_state`,
    which samples a **standard-normal** state — the same convention as
    `resdag.core.ESNModel.set_random_reservoir_states`.  The index is
    therefore directly comparable to states produced elsewhere in the library.

    Parameters
    ----------
    model : ESNModel
        Model containing reservoir layers.
    feedback_seq : torch.Tensor
        Feedback sequence, shape `(batch, timesteps, features)`.
    *driving_seqs : torch.Tensor
        Optional driving sequences in model input order.
    history : bool, default=False
        If True, return full distance history over time.
    iterations : int, default=10
        Number of random initial states to average over.
    transient : int, default=0
        Timesteps to discard from sequence start.
    window : int or None, default=None
        Length of the trailing window over which the index is averaged.  By
        default (`None`) the index is the mean over *every* post-transient
        timestep, which for a healthy reservoir is dominated by the early
        convergence transient rather than the asymptotic distance.  Setting
        `window=k` averages only the **last** `k` post-transient steps, so
        the index reflects the asymptotic regime — a far more diagnostic
        statistic.  Must be a positive integer no larger than the number of
        post-transient timesteps.  Does not affect the returned `history`
        tensors, which always span the full post-transient sequence.
    relative : bool, default=False
        If True, normalise each per-step distance by the corresponding
        base-state norm, `||base - rand|| / (||base|| + eps)`, yielding a
        scale-free relative distance that is comparable across reservoir sizes
        and spectral radii.  If False (default), the raw absolute distance is
        used.  The normalisation is applied to both the returned index and the
        `history` tensors.
    chunk_size : int or None, default=None
        Maximum number of random restarts run together in a single batched
        forward pass.  All restarts are statistically independent and differ
        only in their initial state, so they are folded into the batch
        dimension and evaluated in one forward pass instead of `iterations`
        sequential passes (typically a ~3x speed-up).  A large
        `reservoir_size * iterations` product can exhaust device memory,
        however; set `chunk_size` to cap the per-pass batch at
        `batch * chunk_size` and process the restarts in chunks.  `None`
        (default) runs all `iterations` restarts in one pass, transparently
        falling back to chunking (halving the chunk each time) if a CUDA
        out-of-memory error is raised.
    verbose : bool, default=True
        Print progress and skip messages.

    Returns
    -------
    dict or tuple
        If `history=False`: dict mapping layer names to single-element
        lists containing the ESP index scalar tensor.
        If `history=True`: tuple of (ESP indices dict, history dict).
        History tensors have shape `(iterations, timesteps, batch)` and span
        the full post-transient sequence regardless of `window`.

        Reservoirs whose ESP is undefined (no randomisable state) are omitted
        from both dictionaries.

    Raises
    ------
    ValueError
        If `transient` is not smaller than the number of timesteps, if
        `window` is not a positive integer no larger than the number of
        post-transient timesteps, if the model contains no reservoir layers,
        or if no reservoir has a well-defined ESP.

    Notes
    -----
    For LINEAR systems (identity activation), input does NOT affect ESP
    because the input contribution cancels out in the state difference.
    This is mathematically correct behavior.

    State is never mutated by direct assignment.  The zero base orbit is set
    via `res.reset_state(batch_size=...)` and the random restarts via
    `res.set_random_state()`, so each cell's own shape contract (2-D for
    ESN, 3-D delay buffer for NG-RC) is honoured and validated by the public
    state-management API.

    The caller's reservoir states are saved before the computation and
    restored afterwards (even on error), so calling `esp_index` never leaves
    the model's reservoirs in a mutated (random) state.

    **Batched restarts.**  The `iterations` random restarts are statistically
    independent and differ only in their initial state, so they are folded into
    the batch dimension: the feedback (and any drivers) are tiled `iterations`
    times, one random initial state is composed per restart into a single
    `(batch * iterations, ...)` state, and the whole ensemble is evaluated in
    **one** forward pass rather than `iterations` sequential passes.  The
    random restarts are drawn in exactly the same order as the sequential loop
    (outer over restarts, inner over reservoirs), so the *initial states* are
    bit-identical to the sequential computation.  The reservoir *outputs* — and
    hence the returned index — match the sequential value to floating-point
    rounding (typically `< 1e-6` relative), the only difference being the
    reassociation of a wider batched matmul; the result is fully deterministic
    under a fixed seed.  (If a reservoir cell injects per-step state noise in
    training mode, `noise > 0`, the batched noise draws differ from the
    sequential ones; the index remains a valid, seed-deterministic stochastic
    diagnostic but is no longer numerically identical.  Run the model in eval
    mode to disable noise entirely.)

    Examples
    --------
    Score only the asymptotic regime with a scale-free statistic:

    ```python
    idx = esp_index(model, feedback, window=50, relative=True)
    ```

    See Also
    --------
    resdag.core.ESNModel.set_random_reservoir_states :
        Source of the standard-normal restart convention used here.
    """
    from resdag.data.prepare import _validate_step_count
    from resdag.layers.reservoirs.base_reservoir import BaseReservoirLayer

    iterations = _validate_step_count("iterations", iterations)
    transient = _validate_step_count("transient", transient, allow_zero=True)
    if window is not None:
        window = _validate_step_count("window", window)
    if chunk_size is not None:
        chunk_size = _validate_step_count("chunk_size", chunk_size)

    device = feedback_seq.device
    dtype = feedback_seq.dtype
    batch_size, total_timesteps, _ = feedback_seq.shape

    if transient >= total_timesteps:
        raise ValueError(f"transient ({transient}) >= timesteps ({total_timesteps})")

    timesteps = total_timesteps - transient

    if window is not None and not (0 < window <= timesteps):
        raise ValueError(
            f"window ({window}) must be a positive integer no larger than the "
            f"number of post-transient timesteps ({timesteps})."
        )

    if chunk_size is not None and chunk_size <= 0:
        raise ValueError(f"chunk_size ({chunk_size}) must be a positive integer or None.")

    inputs = (feedback_seq,) + driving_seqs

    # Save the caller's reservoir states *before* any probing/mutation so they
    # can be restored on the way out (including on error).  ``esp_index`` is a
    # read-only diagnostic; it must not leave the model's reservoirs in the
    # random state it uses internally.  ``_has_well_defined_esp`` and the base
    # orbit below both mutate state, so the snapshot has to be taken here first.
    # ``get_reservoir_states`` omits reservoirs whose state is ``None`` (never
    # warmed up), so those names are tracked separately and reset back to
    # ``None`` on restore instead of being left holding an internal state.
    saved_states = model.get_reservoir_states()
    reservoirs_with_none_state = [
        module
        for module in model.modules()
        if isinstance(module, BaseReservoirLayer) and module.state is None
    ]

    try:
        # Discover every reservoir layer (cell-agnostic): any
        # BaseReservoirLayer, not just ESNLayer.  This includes NGReservoirLayer and
        # any custom-cell layer.
        all_reservoirs: list[tuple[str, "BaseReservoirLayer"]] = []
        for name, module in model.named_modules():
            if isinstance(module, BaseReservoirLayer):
                all_reservoirs.append((name, module))

        if not all_reservoirs:
            raise ValueError("No reservoir layers found in model.")

        # Partition reservoirs into those with a well-defined ESP (a non-empty,
        # randomisable state) and those without.  A reservoir with no per-sample
        # state — e.g. a ``k=1`` NG-RC delay buffer of size 0 — has no notion of
        # "different initial states converging", so its ESP is undefined.
        reservoirs: list[tuple[str, "BaseReservoirLayer"]] = []
        for name, res in all_reservoirs:
            if _has_well_defined_esp(res, batch_size):
                reservoirs.append((name, res))
            elif verbose:
                label = name or type(res).__name__
                print(
                    f"Skipping reservoir '{label}': ESP is undefined "
                    f"(reservoir carries no randomisable state)."
                )

        if not reservoirs:
            raise ValueError(
                "No reservoir with a well-defined ESP found in model "
                "(every reservoir carries an empty state)."
            )

        # Run base orbit from the zero initial state.  Routed through the
        # public, validating, cloning API instead of assigning ``res.state``.
        for _, res in reservoirs:
            res.reset_state(batch_size=batch_size)

        base_states = _run_and_collect(model, reservoirs, inputs)
        if transient > 0:
            base_states = {name: s[:, transient:, :] for name, s in base_states.items()}

        # Evaluate all random restarts.  They are statistically independent and
        # differ only in their initial state, so they fold into the batch
        # dimension and run in one (or a few chunked) forward passes instead of
        # ``iterations`` sequential ones.
        random_states_by_iter = _collect_random_restarts(
            model,
            reservoirs,
            inputs,
            batch_size=batch_size,
            iterations=iterations,
            transient=transient,
            device=device,
            dtype=dtype,
            chunk_size=chunk_size,
            verbose=verbose,
        )

        esp_sums = {name: torch.tensor(0.0, device=device, dtype=dtype) for name, _ in reservoirs}
        if history:
            esp_history = {
                name: torch.zeros(iterations, timesteps, batch_size, device=device, dtype=dtype)
                for name, _ in reservoirs
            }

        # Reduce per restart.  Splitting the batched outputs back into
        # per-restart blocks and reducing them one at a time reproduces the
        # sequential arithmetic exactly (same per-iteration mean, then mean over
        # iterations), so ``window`` / ``relative`` / ``history`` behave
        # identically to the sequential path.
        for i in range(iterations):
            random_states = random_states_by_iter[i]
            for name, base in base_states.items():
                rand = random_states[name]
                # Distance at each (batch, timestep): norm over the feature
                # dimension.  Works for any output rank the reservoir produces.
                dist = torch.norm(base - rand, dim=-1)  # (batch, timesteps)

                if relative:
                    # Scale-free relative distance: divide by the base-state
                    # norm so the index is comparable across sizes / radii.
                    base_norm = torch.norm(base, dim=-1)  # (batch, timesteps)
                    dist = dist / (base_norm + 1e-12)

                # Mean distance for this restart.  With ``window`` set, average
                # only over the trailing window (the asymptotic regime);
                # otherwise over every post-transient timestep.
                dist_for_index = dist[:, -window:] if window is not None else dist
                esp_sums[name] += dist_for_index.mean()

                if history:
                    # Store the full post-transient sequence regardless of
                    # window: (batch, timesteps) -> row i of
                    # (iterations, timesteps, batch).
                    esp_history[name][i] = dist.T  # Transpose to (timesteps, batch)

        # Average over iterations
        esp_indices = {name: [val / iterations] for name, val in esp_sums.items()}

        if history:
            # Wrap history values in lists for API consistency
            esp_history_out = {name: [h] for name, h in esp_history.items()}
            return esp_indices, esp_history_out

        return esp_indices
    finally:
        # Restore the caller's reservoir states, whatever happened above.  Use
        # ``strict=False`` because reservoirs skipped as ESP-undefined (or any
        # that had no state to begin with) are simply absent from the snapshot.
        model.set_reservoir_states(saved_states, strict=False)
        # Reservoirs that started with a ``None`` state (never warmed up) are
        # absent from the snapshot, so ``set_reservoir_states`` would leave them
        # holding an internal state.  Reset them back to ``None`` to fully
        # restore the caller's pre-call condition.
        for module in reservoirs_with_none_state:
            module.reset_state()

seed_everything explicitly seeds process-wide Python, NumPy and Torch RNGs. Prefer local generators or SeedStreams when independent components should not share or advance one global stream. resolve_device resolves the requested device; it does not move model parameters or data.