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 ( |
create_rng |
Create a NumPy random number generator with optional seed. |
create_torch_generator |
Create a torch |
coerce_seed_to_int |
Reduce an int/ |
SeedStreams |
Derive stable seeds for explicitly named model components. |
SeedLike |
Type alias for accepted seed inputs ( |
DeviceLike |
Type alias for accepted device specs ( |
load_file |
Load a time series from disk (re-exported from |
prepare_esn_data |
Split a series into ESN train/forecast segments (re-exported from
|
normalize_data |
Normalize a series and return the fitted statistics (re-exported from
|
denormalize_data |
Invert a normalization back to the original scale (re-exported from
|
lorenz, rossler, henon, mackey_glass, narma, sine |
Canonical reservoir-computing dataset generators (re-exported from
|
esp_index |
Echo State Property index — the library's signature stability diagnostic
(re-exported from |
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.
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
¶
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 | |
create_rng
¶
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
TYPE:
|
| 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 | |
create_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.
| PARAMETER | DESCRIPTION |
|---|---|
seed
|
If
TYPE:
|
device
|
Device for the new generator. Ignored when
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Generator
|
A generator suitable for passing to |
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 | |
coerce_seed_to_int
¶
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:
|
| RETURNS | DESCRIPTION |
|---|---|
int or 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 | |
seed_everything
¶
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:
|
deterministic
|
If |
| RETURNS | DESCRIPTION |
|---|---|
int
|
The |
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 | |
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
|
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
device
|
The resolved device. |
| RAISES | DESCRIPTION |
|---|---|
TypeError
|
If |
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 | |
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:
|
feedback_seq
|
Feedback sequence, shape
TYPE:
|
*driving_seqs
|
Optional driving sequences in model input order.
TYPE:
|
history
|
If True, return full distance history over time.
TYPE:
|
iterations
|
Number of random initial states to average over.
TYPE:
|
transient
|
Timesteps to discard from sequence start.
TYPE:
|
window
|
Length of the trailing window over which the index is averaged. By
default (
TYPE:
|
relative
|
If True, normalise each per-step distance by the corresponding
base-state norm,
TYPE:
|
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
TYPE:
|
verbose
|
Print progress and skip messages.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict or tuple
|
If Reservoirs whose ESP is undefined (no randomisable state) are omitted from both dictionaries. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
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 | |
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.