Reference
Initialization¶
How frozen weights get their values: topology initializers for the square recurrent matrix, input/feedback initializers for the rectangular ones, the registries behind both, and the resolvers that accept names, tuples, callables, or configured objects interchangeably.
Use recurrent_initializer= for recurrent graph or matrix weights and
feedback_initializer= / input_initializer= for rectangular projections.
These configure frozen weights; the reservoir cell still determines the state
update equation. Registry decorators, initializer base classes and callable
specifications remain supported extension interfaces. See
custom components for complete recipes.
Recurrent initializers¶
recurrent
¶
Discover, register, and configure recurrent weight initializers.
The registry is shared with resdag.init.topology: existing graph and
matrix registrations work with both APIs. A recurrent initializer specifies
the recurrent weights; the reservoir cell specifies the state update equation.
get_recurrent_initializer
¶
get_recurrent_initializer(
name: str, *, rescale: bool | None = None, **builder_kwargs: Any
) -> TopologyInitializer
Configure a registered graph or matrix recurrent initializer.
rescale=None retains the registration's policy: ordinary builders are
scaled to a requested layer radius, while prescaled builders preserve
their own spectrum and warn on a conflicting layer radius.
rescale=False explicitly skips outer spectral estimation/scaling.
rescale=True explicitly applies a requested layer radius, even for a
prescaled builder. With no layer radius, neither choice changes weights.
For example, use
get_recurrent_initializer("fast_spectral_initialization", spectral_radius=0.9, rescale=False) for FSI's approximate analytic scale
without an outer eigendecomposition. The old get_topology API and
tuple specs continue forwarding arbitrary keywords to custom builders.
Source code in src/resdag/init/recurrent.py
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 | |
register_recurrent_initializer
¶
register_recurrent_initializer(
name: str, prescaled: bool = False, **default_kwargs: Any
) -> Callable[[Callable], Callable]
Register a direct matrix builder in the shared recurrent registry.
Builders accept n followed by their parameters and return an (n, n)
matrix. prescaled=True preserves a builder's spectral profile by
default; an explicit rescale=True configuration can override it.
Graph builders continue to use register_graph_topology.
Source code in src/resdag/init/recurrent.py
22 23 24 25 26 27 28 29 30 31 32 33 34 | |
show_recurrent_initializers
¶
List all graph and matrix initializers, or inspect a named builder.
This is the same registry exposed by show_topologies, so existing
custom registrations are included automatically.
Source code in src/resdag/init/recurrent.py
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | |
Topologies and custom builders¶
topology
¶
Topology Initialization System¶
This module provides the interface between structure generators — NetworkX graphs or direct matrix builders — and PyTorch tensor initialization for reservoir recurrent weights.
| CLASS | DESCRIPTION |
|---|---|
TopologyInitializer |
Abstract base class for topology initializers. |
GraphTopology |
Concrete implementation using NetworkX graphs. |
MatrixTopology |
Concrete implementation wrapping any matrix-building callable. |
| FUNCTION | DESCRIPTION |
|---|---|
get_topology |
Get a pre-configured topology by name. |
show_topologies |
List available topologies or get details. |
register_graph_topology |
Decorator to register graph-based topologies. |
register_matrix_topology |
Decorator to register matrix-builder topologies. |
scale_to_spectral_radius |
Rescale a square matrix to a target spectral radius. |
estimate_spectral_radius |
Measure the largest absolute eigenvalue using dense eigvals, sparse Arnoldi or analytic triangular/weighted-cycle structure. CSR failures above size two never allocate a dense fallback. |
Examples:
Using pre-registered topologies:
>>> from resdag.init.topology import get_topology
>>> topology = get_topology("erdos_renyi", p=0.1, seed=42)
>>> weight = torch.empty(100, 100)
>>> topology.initialize(weight, spectral_radius=0.9)
Any function that builds a matrix is a topology:
>>> def block_diagonal(n, blocks=4):
... ... # return an (n, n) tensor
>>> reservoir = ESNLayer(500, feedback_size=3, topology=block_diagonal)
Registering custom topologies:
>>> from resdag.init.topology import register_graph_topology, register_matrix_topology
>>> @register_graph_topology("custom", param=1.0)
... def my_custom_graph(n, param=1.0, seed=None):
... G = nx.DiGraph()
... # ... graph generation logic
... return G
>>> @register_matrix_topology("block_diagonal", blocks=4)
... def block_diagonal(n, blocks=4, seed=None):
... # ... matrix construction logic
... return w
See Also
resdag.init.graphs : Graph generation functions. resdag.init.matrices : Direct matrix-construction functions. resdag.layers.ESNLayer : Uses topologies for weight initialization.
TopologyInitializer
¶
Bases: ABC
Abstract base class for topology-based weight initialization.
Initializers build recurrent weights from graph structures or direct matrix builders. They take the required size, dtype and device from a destination tensor and optionally apply spectral radius scaling.
Subclasses must implement the initialize method.
| ATTRIBUTE | DESCRIPTION |
|---|---|
prescaled |
Whether the topology bakes its own spectral structure into the
recurrent matrix (graded radii, unit singular values, an analytically
fixed spectral radius, ...). When
TYPE:
|
rescale |
Explicit outer scaling policy. None keeps the registration's
TYPE:
|
See Also
GraphTopology : Concrete implementation using NetworkX graphs. resdag.layers.ESNLayer : Uses topology initializers.
build_sparse
¶
build_sparse(
n: int, *, dtype: dtype, device: device, spectral_radius: float | None = None
) -> Tensor
Build CSR weights; override to avoid a dense initialization scratch.
Existing in-place custom initializers remain usable. Their default implementation needs a temporary dense matrix, released after conversion. GraphTopology builds directly from edges, including bounded ER draws.
Source code in src/resdag/init/topology/base.py
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 | |
initialize
abstractmethod
¶
Initialize a weight tensor using graph topology.
| PARAMETER | DESCRIPTION |
|---|---|
weight
|
The weight tensor to initialize, shape
TYPE:
|
spectral_radius
|
Target spectral radius for scaling. If None, no scaling is applied.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The initialized weight tensor (same as input, modified in-place). |
Source code in src/resdag/init/topology/base.py
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 | |
GraphTopology
¶
GraphTopology(
graph_func: Callable,
graph_kwargs: dict[str, Any] | None = None,
prescaled: bool = False,
rescale: bool | None = None,
)
Bases: TopologyInitializer
Topology initializer based on NetworkX graph functions.
This class wraps a graph generation function and converts it into a weight
initializer. The graph function must accept n (number of nodes) as its
first argument.
| PARAMETER | DESCRIPTION |
|---|---|
graph_func
|
A function with signature
TYPE:
|
graph_kwargs
|
Keyword arguments to pass to the graph function.
TYPE:
|
prescaled
|
If
TYPE:
|
rescale
|
Explicit outer scaling policy. False skips scaling silently; True applies a requested radius even for prescaled graphs. None retains the legacy prescaled policy and warning.
TYPE:
|
| ATTRIBUTE | DESCRIPTION |
|---|---|
graph_func |
The graph generation function.
TYPE:
|
graph_kwargs |
Keyword arguments for the graph function.
TYPE:
|
prescaled |
Whether the outer spectral-radius rescale is suppressed (see above).
TYPE:
|
Examples:
Using a registered graph function:
>>> from resdag.init.graphs import erdos_renyi_graph
>>> import torch
>>>
>>> topology = GraphTopology(erdos_renyi_graph, {"p": 0.1, "directed": True})
>>> weight = torch.empty(100, 100)
>>> topology.initialize(weight, spectral_radius=0.9)
With the registry helper:
>>> from resdag.init.topology import get_topology
>>> topology = get_topology("erdos_renyi", p=0.15)
>>> topology.initialize(weight, spectral_radius=0.95)
See Also
resdag.init.graphs : Available graph generation functions. get_topology : Get pre-configured topology by name.
Source code in src/resdag/init/topology/base.py
525 526 527 528 529 530 531 532 533 534 535 536 537 | |
initialize
¶
Initialize weight tensor from graph topology.
Generates a graph using the stored function, converts it to an adjacency matrix, and optionally scales to the target spectral radius.
When this topology is prescaled, the outer spectral-radius
rescale is skipped (the builder's own spectral structure is kept) and a
warning is emitted if spectral_radius is not None. An explicit
rescale policy overrides this: False skips silently, True scales.
| PARAMETER | DESCRIPTION |
|---|---|
weight
|
Square tensor to initialize, shape
TYPE:
|
spectral_radius
|
Target spectral radius for the weight matrix. Ignored (with a
warning) when the topology is
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Initialized weight tensor (modified in-place). |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If weight is not 2D or not square. |
Source code in src/resdag/init/topology/base.py
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 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 | |
build_sparse
¶
build_sparse(
n: int, *, dtype: dtype, device: device, spectral_radius: float | None = None
) -> Tensor
Build from graph edges without a dense Torch adjacency allocation.
Source code in src/resdag/init/topology/base.py
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 | |
MatrixTopology
¶
MatrixTopology(
matrix_func: Callable,
matrix_kwargs: dict[str, Any] | None = None,
prescaled: bool = False,
seed: int | None = None,
rescale: bool | None = None,
)
Bases: TopologyInitializer
Topology initializer wrapping any matrix-building callable.
This is the general-purpose escape hatch of the topology system: any
function with logic for constructing a recurrent weight matrix becomes a
topology, with full access to spectral-radius scaling, the registry, and
the ESNLayer(topology=...) shorthand. No graph required.
Two calling conventions are supported, tried in order:
- Build style —
fn(n, **kwargs)returning an(n, n)array-like: atorch.Tensor, anumpy.ndarray, or even anetworkxgraph (converted to its adjacency matrix). - In-place style —
fn(tensor, **kwargs)mutating a tensor in place, e.g. anytorch.nn.init.*_function.
| PARAMETER | DESCRIPTION |
|---|---|
matrix_func
|
The matrix-building function (build style or in-place style).
TYPE:
|
matrix_kwargs
|
Keyword arguments bound to the function.
TYPE:
|
prescaled
|
If
TYPE:
|
seed
|
Reproducibility seed for in-place builders that take a
TYPE:
|
rescale
|
Explicit outer scaling policy. False skips spectral estimation and scaling silently; True applies a requested layer radius even for a prescaled builder. None retains the legacy policy and warning.
TYPE:
|
Notes
Build-style callbacks with explicit dtype or device parameters
receive the destination's values unless matrix_kwargs already binds
them. This lets built-in builders compute directly in float64 or on CUDA
instead of casting a prebuilt float32 CPU matrix. Generic **kwargs
callbacks receive no additional placement keywords. MPS spectral-radius
measurements use CPU because MPS does not implement complex eigvals.
Examples:
A plain function as a topology:
>>> import torch
>>> def block_diagonal(n, blocks=4):
... w = torch.zeros(n, n)
... size = n // blocks
... for b in range(blocks):
... s = b * size
... w[s : s + size, s : s + size] = torch.randn(size, size)
... return w
>>> topology = MatrixTopology(block_diagonal, {"blocks": 5})
>>> weight = torch.empty(100, 100)
>>> topology.initialize(weight, spectral_radius=0.9)
Bare callables passed to ESNLayer are wrapped automatically:
>>> from resdag.layers import ESNLayer
>>> layer = ESNLayer(100, feedback_size=3, topology=block_diagonal)
>>> layer = ESNLayer(100, feedback_size=3, topology=(block_diagonal, {"blocks": 2}))
torch.nn.init functions work directly (in-place style):
>>> layer = ESNLayer(100, feedback_size=3, topology=torch.nn.init.orthogonal_)
See Also
GraphTopology : Graph-based topologies. resdag.init.topology.register_matrix_topology : Register by name.
Source code in src/resdag/init/topology/base.py
798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 | |
build_sparse
¶
build_sparse(
n: int, *, dtype: dtype, device: device, spectral_radius: float | None = None
) -> Tensor
Accept registered builders returning CSR/SciPy sparse data.
Build-style callables need no dense destination. In-place callables allocate their scratch tensor lazily through the shared convention.
Source code in src/resdag/init/topology/base.py
814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 | |
initialize
¶
Initialize a square weight tensor from the wrapped callable.
When this topology is prescaled, the outer spectral-radius
rescale is skipped (the builder's own spectral structure is kept) and a
warning is emitted if spectral_radius is not None. An explicit
rescale policy overrides this: False skips silently, True scales.
| PARAMETER | DESCRIPTION |
|---|---|
weight
|
Square tensor to initialize, shape
TYPE:
|
spectral_radius
|
Target spectral radius. If None, no scaling is applied. Ignored
(with a warning) when the topology is
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Initialized weight tensor (modified in-place). |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Source code in src/resdag/init/topology/base.py
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 | |
get_topology
¶
get_topology(name: str, **override_kwargs: Any) -> TopologyInitializer
Get a pre-configured topology initializer by name.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
Name of the topology (e.g.,
TYPE:
|
**override_kwargs
|
Keyword arguments to override default graph parameters.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
TopologyInitializer
|
Configured topology initializer ( |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If topology name is not registered. |
Examples:
Basic usage:
>>> topology = get_topology("erdos_renyi", p=0.15, seed=42)
>>> weight = torch.empty(100, 100)
>>> topology.initialize(weight, spectral_radius=0.9)
With ESNLayer:
>>> from resdag.layers import ESNLayer
>>> reservoir = ESNLayer(
... reservoir_size=500,
... feedback_size=10,
... topology=get_topology("watts_strogatz", k=4, p=0.3),
... spectral_radius=0.95,
... )
See Also
show_topologies : List available topologies. register_graph_topology : Register new topologies.
Source code in src/resdag/init/topology/registry.py
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 | |
register_graph_topology
¶
register_graph_topology(
name: str, prescaled: bool = False, **default_kwargs: Any
) -> Callable[[Callable], Callable]
Decorator to register a graph function as a topology.
Registers a graph generation function in the topology registry at
definition time, making it available for use with
resdag.layers.ESNLayer.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
Unique name for the topology.
TYPE:
|
prescaled
|
Mark the topology as already carrying its own spectral structure (e.g.
TYPE:
|
**default_kwargs
|
Default keyword arguments for the graph function.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
callable
|
Decorator function that registers and returns the graph function. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If a topology with the same name is already registered. |
Examples:
>>> @register_graph_topology("my_graph", p=0.1, directed=True)
... def my_graph(n, p=0.1, directed=False, seed=None):
... G = nx.DiGraph() if directed else nx.Graph()
... # ... graph generation logic
... return G
Notes
- Graph functions must accept
n(number of nodes) as first parameter. - Graph functions must return
nx.Graphornx.DiGraphwith weighted edges. - Registered topologies can be accessed via
get_topology.
Source code in src/resdag/init/topology/registry.py
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 | |
register_matrix_topology
¶
register_matrix_topology(
name: str, prescaled: bool = False, **default_kwargs: Any
) -> Callable[[Callable], Callable]
Decorator to register a matrix-building function as a topology.
The complement of register_graph_topology for builders that
construct the recurrent weight matrix directly — no graph involved.
Any logic that produces a square matrix qualifies.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
Unique name for the topology.
TYPE:
|
prescaled
|
Mark the topology as already fixing its own spectral structure (e.g.
TYPE:
|
**default_kwargs
|
Default keyword arguments for the matrix function.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
callable
|
Decorator function that registers and returns the matrix function. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If a topology with the same name is already registered. |
Examples:
>>> @register_matrix_topology("block_diagonal", blocks=4)
... def block_diagonal(n, blocks=4, seed=None):
... w = torch.zeros(n, n)
... size = n // blocks
... for b in range(blocks):
... s = b * size
... w[s : s + size, s : s + size] = torch.randn(size, size)
... return w
>>> reservoir = ESNLayer(500, feedback_size=3, topology="block_diagonal")
Notes
- Matrix functions must accept
n(matrix size) as first parameter and return an(n, n)torch.Tensorornumpy.ndarray. - Registered topologies are accessed via
get_topologyor by name inESNLayer(topology="..."), identically to graph topologies.
Source code in src/resdag/init/topology/registry.py
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 | |
estimate_spectral_radius
¶
Estimate the spectral radius (largest |eigenvalue|) of a matrix.
Dense inputs use torch.linalg.eigvals, or SciPy's sparse Arnoldi
solver (which="LM") for large matrices with density at most 0.1, with
a dense fallback if Arnoldi is unavailable or unsuccessful. CSR inputs use
analytic zero, triangular and weighted-cycle cases when applicable, then
Arnoldi; failure raises without allocating a dense fallback. Only CSR sizes
1--2 use a bounded dense solve. Arnoldi is an iterative numerical
approximation; requesting several dominant eigenvalues reduces sensitivity
to clustered spectra.
A stationary power-iteration estimate does not establish that the dominant
eigenspace was found, so it is never used for automatic spectral scaling.
Dense eigendecomposition can be expensive at large sizes. Use a builder with
known spectral structure and prescaled=True to avoid this measurement.
MPS inputs are measured on CPU because MPS lacks complex eigensolves.
| PARAMETER | DESCRIPTION |
|---|---|
matrix
|
Square matrix whose spectral radius is wanted.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
The estimated largest absolute eigenvalue |
See Also
scale_to_spectral_radius : Uses this to rescale a matrix to a target radius.
Source code in src/resdag/init/topology/base.py
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 | |
scale_to_spectral_radius
¶
Rescale a square matrix so its spectral radius equals target_radius.
The current spectral radius is obtained from
estimate_spectral_radius, which uses analytic structured-CSR cases,
dense eigvals or sparse Arnoldi. General CSR failure raises without a
dense fallback; dense inputs retain their dense fallback. Returns the
matrix unchanged when its current measured spectral radius is zero — e.g.
the zero topology or a nilpotent matrix.
This is the single shared rescale implementation used by both
GraphTopology/MatrixTopology and
resdag.layers.cells.esn_cell.ESNCell.
| PARAMETER | DESCRIPTION |
|---|---|
matrix
|
Square matrix to rescale.
TYPE:
|
target_radius
|
Desired largest absolute eigenvalue.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The rescaled matrix (new tensor). |
Source code in src/resdag/init/topology/base.py
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 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 | |
show_topologies
¶
Show available topologies or details for a specific topology.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
Name of topology to inspect. If None, prints all registered topology names and returns them as a list.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list of str or None
|
When |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the specified topology name is not registered. |
Source code in src/resdag/init/topology/registry.py
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 | |
Input and feedback initializers¶
input_feedback
¶
Input/Feedback Weight Initialization¶
This module contains initializers for rectangular weight matrices used in reservoir input and feedback connections.
For reservoirs:
- Feedback weights: (reservoir_size, feedback_size)
- Input weights: (reservoir_size, input_size)
| CLASS | DESCRIPTION |
|---|---|
InputFeedbackInitializer |
Abstract base class for all initializers. |
RandomInputInitializer |
Uniform random in [-1, 1] (baseline). |
RandomBinaryInitializer |
Binary {-1, +1} values. |
NormalInputInitializer |
Gaussian |
UniformInputInitializer |
Bounded |
BernoulliInputInitializer |
Bernoulli |
PseudoDiagonalInitializer |
Structured block-diagonal pattern. |
ChebyshevInitializer |
Deterministic chaotic initialization. |
LogisticMappingInitializer |
Deterministic logistic-map initialization (RC.jl |
MinimalInputInitializer |
Rodan & Tiňo minimal-complexity dense input (RC.jl |
WeightedInputInitializer |
Block-diagonal random input (RC.jl |
WeightedMinimalInitializer |
Block-diagonal constant-magnitude input (RC.jl |
InformedInputInitializer |
State/model split for hybrid ESNs (RC.jl |
ChessboardInitializer |
Alternating {-1, +1} pattern. |
BinaryBalancedInitializer |
Hadamard-based balanced initialization. |
OppositeAnchorsInitializer |
Opposite anchor points on ring. |
DendrocycleInputInitializer |
Specific to dendrocycle topology. |
ChainOfNeuronsInputInitializer |
Specific to chain-of-neurons topology. |
RingWindowInputInitializer |
Windowed inputs on ring topology. |
ZeroInitializer |
Sets all weights to zero. |
FunctionInitializer |
Wraps any matrix-building callable as an initializer (the input/feedback analog of a matrix-builder topology). |
| FUNCTION | DESCRIPTION |
|---|---|
get_input_feedback |
Get an initializer by name. |
show_input_initializers |
List available initializers or get details. |
register_input_feedback |
Decorator to register new initializers. |
Examples:
Using pre-registered initializers:
>>> from resdag.init.input_feedback import get_input_feedback
>>> initializer = get_input_feedback("random", input_scaling=0.5)
>>> weight = torch.empty(100, 10)
>>> initializer.initialize(weight)
Registering custom initializers:
>>> from resdag.init.input_feedback import register_input_feedback
>>> @register_input_feedback("my_init", scaling=0.5)
... class MyInitializer(InputFeedbackInitializer):
... def __init__(self, scaling=0.5):
... self.scaling = scaling
... def initialize(self, weight, **kwargs):
... torch.nn.init.uniform_(weight, -self.scaling, self.scaling)
... return weight
See Also
resdag.layers.ESNLayer : Uses these initializers for weight matrices. resdag.init.topology : Topology initializers for recurrent weights.
InputFeedbackInitializer
¶
InputFeedbackInitializer(
input_scaling: float | None = None,
connectivity: float | None = None,
seed: SeedLike = None,
)
Bases: ABC
Abstract base class for input/feedback weight initialization.
All input/feedback weight initializers inherit from this class, implement
initialize, and honor the shared scaling contract owned here.
These initializers create weight matrices for:
- Input connections: shape
(reservoir_size, input_size) - Feedback connections: shape
(reservoir_size, feedback_size)
The scaling contract
input_scaling is the single uniform magnitude knob:
None— no scaling; the natural-range matrix is returned as-is.s(finite float) — multiply the whole matrix bysas the documented final transform, so the matrix's magnitude statistic (max|W|for elementwise initializers, per-channel L2 norm for the structured ring initializers) scales linearly withs.
connectivity is an optional density knob in (0, 1]: the fraction of
nonzero entries kept per column. None leaves the produced sparsity
untouched.
Per-call overrides
The contract parameters are bound at construction, but initialize
(and the __call__ alias) accept per-call keyword overrides for
the recognized contract parameters — input_scaling and connectivity.
A recognized keyword passed to initialize takes precedence over the
bound attribute for that call only, and is validated identically:
init = RandomInputInitializer(input_scaling=2.0)
init.initialize(weight) # uses input_scaling=2.0
init.initialize(weight, input_scaling=0.001) # honored: uses 0.001
init.input_scaling # still 2.0 (unchanged)
This is the same contract FunctionInitializer honors (per-call
kwargs merged over the bound ones), so a given call shape behaves
identically for class-based and function-wrapped initializers. Subclasses
cooperate simply by threading their **kwargs into the contract helpers,
which read the override from **kwargs and fall back to the bound
attribute; unrecognized keys are ignored.
Subclasses must implement initialize, which builds the weight
tensor and returns it (modified in-place). They opt into the contract via
_apply_scaling (and optionally _apply_connectivity),
forwarding the per-call **kwargs so recognized overrides are honored.
| PARAMETER | DESCRIPTION |
|---|---|
input_scaling
|
Uniform multiplicative scaling applied as the final transform.
TYPE:
|
connectivity
|
Fraction of nonzero entries to keep per column, in
TYPE:
|
seed
|
Reproducibility seed for any subclass randomness (the uniform/binary
draws of the random initializers) and the connectivity mask. Accepts a
plain
TYPE:
|
Examples:
Creating a custom initializer that honors the contract:
>>> class MyInitializer(InputFeedbackInitializer):
... def initialize(self, weight, **kwargs):
... values = torch.empty_like(weight).uniform_(-1, 1)
... # Forward **kwargs so a per-call ``input_scaling`` override wins.
... values = self._apply_scaling(values, **kwargs)
... with torch.no_grad():
... weight.copy_(values)
... return weight
>>>
>>> initializer = MyInitializer(input_scaling=0.5)
>>> weight = torch.empty(100, 10)
>>> initializer(weight)
Using with ESNLayer:
>>> from resdag.layers import ESNLayer
>>> reservoir = ESNLayer(
... reservoir_size=100,
... feedback_size=10,
... feedback_initializer=MyInitializer(input_scaling=0.5),
... )
See Also
resdag.init.input_feedback.registry : Get initializers by name. resdag.layers.ESNLayer : Uses these initializers.
Source code in src/resdag/init/input_feedback/base.py
166 167 168 169 170 171 172 173 174 175 | |
initialize
abstractmethod
¶
Initialize a weight tensor.
| PARAMETER | DESCRIPTION |
|---|---|
weight
|
2D tensor of shape
TYPE:
|
**kwargs
|
Per-call keyword overrides. The recognized contract parameters —
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The initialized weight tensor (same as input, modified in-place). |
Source code in src/resdag/init/input_feedback/base.py
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 | |
FunctionInitializer
¶
Bases: InputFeedbackInitializer
Input/feedback initializer wrapping any matrix-building callable.
Lets plain functions act as initializers for the rectangular input and feedback weight matrices, without subclassing. Two calling conventions are supported, tried in order:
- Build style —
fn(rows, cols, **kwargs)returning a(rows, cols)array-like (torch.Tensorornumpy.ndarray). - In-place style —
fn(tensor, **kwargs)mutating a tensor in place, e.g. anytorch.nn.init.*_function.
| PARAMETER | DESCRIPTION |
|---|---|
fn
|
The matrix-building function (build style or in-place style).
TYPE:
|
**kwargs
|
Keyword arguments bound to the function.
TYPE:
|
Examples:
A plain function as an initializer:
>>> import torch
>>> def first_neuron_only(rows, cols, scale=1.0):
... w = torch.zeros(rows, cols)
... w[0, :] = scale
... return w
>>> init = FunctionInitializer(first_neuron_only, scale=0.5)
>>> weight = torch.empty(100, 3)
>>> init.initialize(weight)
Bare callables passed to ESNLayer are wrapped automatically:
>>> from resdag.layers import ESNLayer
>>> layer = ESNLayer(100, feedback_size=3, feedback_initializer=first_neuron_only)
>>> layer = ESNLayer(
... 100,
... feedback_size=3,
... feedback_initializer=(first_neuron_only, {"scale": 0.1}),
... )
torch.nn.init functions work directly (in-place style):
>>> layer = ESNLayer(100, feedback_size=3, feedback_initializer=torch.nn.init.xavier_uniform_)
See Also
InputFeedbackInitializer : Base class for class-based initializers. resdag.init.input_feedback.register_input_feedback : Register by name.
Source code in src/resdag/init/input_feedback/function.py
78 79 80 81 | |
initialize
¶
Initialize a rectangular weight tensor from the wrapped callable.
| PARAMETER | DESCRIPTION |
|---|---|
weight
|
2D tensor of shape
TYPE:
|
**kwargs
|
Per-call overrides merged over the bound keyword arguments (a
recognized key wins for this call only). This is the same per-call
contract the class-based initializers honor — see the Per-call
overrides section of
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The initialized weight tensor (same as input, modified in-place). |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Source code in src/resdag/init/input_feedback/function.py
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 | |
InformedInputInitializer
¶
InformedInputInitializer(
model_in_size: int | None = None,
gamma: float = 0.5,
input_scaling: float | None = 0.1,
seed: int | None = None,
)
Bases: InputFeedbackInitializer
Informed input layer for hybrid/knowledge ESNs (RC.jl informed_init [Pathak2018]).
Splits the reservoir units into a "state" group and a "model" group so a
hybrid ESN can wire the raw system state and the knowledge-based model output
into disjoint fractions of the reservoir. The input columns are partitioned
the same way: the first state_size = in_size - model_in_size columns are
the raw state channels; the trailing model_in_size columns are the model
channels.
Construction (mirrors RC.jl informed_init):
state_size = in_size - model_in_size(must be> 0).num_for_state = floor(reservoir_size * gamma)reservoir rows receive a single random connection to a randomly chosen state column[0, state_size).num_for_model = floor(reservoir_size * (1 - gamma))reservoir rows receive a single random connection to a randomly chosen model column[state_size, in_size).
Each chosen entry is a random value in [-input_scaling, input_scaling]
(RC.jl: (rand - 0.5) * 2 * scaling). Candidate rows are drawn only from
rows that are still all-zero, so a unit gets at most one input
connection; when fewer zero rows remain than requested the loop stops early
(RC.jl's isempty(...) && break). All other entries are zero.
gamma is the fraction of the reservoir devoted to the raw state, so
gamma near 1 weights the reservoir toward the state and near 0
toward the knowledge model. A later HybridESN phase consumes this
initializer to build its input matrix.
| PARAMETER | DESCRIPTION |
|---|---|
model_in_size
|
Number of model input channels (RC.jl
TYPE:
|
gamma
|
Fraction of reservoir units wired to the raw state block (RC.jl
TYPE:
|
input_scaling
|
Half-width of the uniform draw for each connection: values land in
TYPE:
|
seed
|
Reproducibility seed for the row/column choices and value draws.
TYPE:
|
References
J. Pathak et al., "Hybrid forecasting of chaotic processes: Using machine learning in conjunction with a knowledge-based model," Chaos, vol. 28, no. 4, 041101, 2018.
ReservoirComputing.jl informed_init (src/inits/inits_input.jl).
Examples:
>>> from resdag.init.input_feedback import InformedInputInitializer
>>>
>>> # 3 input channels: 1 model column, 2 state columns; half the reservoir
>>> # wired to the state block.
>>> init = InformedInputInitializer(model_in_size=1, gamma=0.5, seed=42)
>>> weight = torch.empty(10, 3)
>>> init.initialize(weight)
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Source code in src/resdag/init/input_feedback/informed.py
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 | |
initialize
¶
Fill the informed (state/model split) input weight.
| PARAMETER | DESCRIPTION |
|---|---|
weight
|
Weight tensor of shape
TYPE:
|
**kwargs
|
Per-call keyword overrides. A recognized
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The initialized weight tensor (modified in-place). |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Source code in src/resdag/init/input_feedback/informed.py
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 | |
LogisticMappingInitializer
¶
LogisticMappingInitializer(
amplitude: float = 0.3,
sine_divisor: float = 5.9,
logistic_parameter: float = 3.7,
input_scaling: float | None = None,
)
Bases: InputFeedbackInitializer
Logistic-map input initializer (RC.jl logistic_mapping [Wang2022]).
A deterministic-chaos initializer, structurally the logistic-map sibling of
resdag.init.input_feedback.ChebyshevInitializer but generated
row-wise (down the reservoir axis) rather than column-wise. The first row
is a sine seed and each subsequent row is one logistic-map iteration of the
row above.
Construction (mirrors RC.jl logistic_mapping):
- First row:
W[0, j] = amplitude * sin((j + 1) * pi / (sine_divisor * in_size))for columnj(RC.jl is 1-indexed, so columnjusesj + 1). - Subsequent rows:
W[i, j] = logistic_parameter * W[i-1, j] * (1 - W[i-1, j]).
Unlike Chebyshev, entries are not in [-1, 1] — the logistic orbit
lives in [0, 1] for the default parameters — and columns are not
peak-normalized, faithfully reproducing RC.jl.
| PARAMETER | DESCRIPTION |
|---|---|
amplitude
|
Sine amplitude for the first-row seed (RC.jl
TYPE:
|
sine_divisor
|
Divisor in the sine phase (RC.jl
TYPE:
|
logistic_parameter
|
Growth rate
TYPE:
|
input_scaling
|
Uniform magnitude knob from the shared scaling contract.
TYPE:
|
References
X. Wang et al. (logistic-map ESN input initialization), 2022.
ReservoirComputing.jl logistic_mapping (src/inits/inits_input.jl).
Examples:
>>> from resdag.init.input_feedback import LogisticMappingInitializer
>>>
>>> init = LogisticMappingInitializer()
>>> weight = torch.empty(8, 3)
>>> init.initialize(weight)
Source code in src/resdag/init/input_feedback/logistic_mapping.py
67 68 69 70 71 72 73 74 75 76 77 78 | |
initialize
¶
Initialize the weight via the logistic map.
| PARAMETER | DESCRIPTION |
|---|---|
weight
|
Weight tensor of shape
TYPE:
|
**kwargs
|
Per-call keyword overrides. A recognized
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The initialized weight tensor (modified in-place). |
Source code in src/resdag/init/input_feedback/logistic_mapping.py
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 | |
MinimalInputInitializer
¶
MinimalInputInitializer(
weight: float = 0.1,
sign_rule: str = "bernoulli",
positive_prob: float = 0.5,
start: int = 1,
strides: int = 2,
input_scaling: float | None = None,
seed: int | None = None,
)
Bases: InputFeedbackInitializer
Minimal-complexity input weights (Rodan & Tiňo; RC.jl minimal_init).
Every entry of the input matrix has the same magnitude weight; only
the sign varies, chosen by a deterministic or stochastic sign_rule. This
is the "minimal complexity" input layer of Rodan & Tiňo — a single weight
magnitude across all input-to-reservoir connections, paired with a simple
cycle reservoir — which they show rivals fully random ESNs on many tasks.
The matrix is dense: every reservoir unit receives every input (unlike
WeightedMinimalInitializer, whose connections are block-diagonal).
Construction (mirrors RC.jl minimal_init):
- Fill an
(reservoir_size, in_size)matrix with the constantweight. - Apply the
sign_rulein RC.jl's column-major traversal order.
Sign rules (RC.jl sampling_type):
"bernoulli"(default) — each entry keeps its+sign with probabilitypositive_proband is negated otherwise (RC.jlbernoulli_sample!). This is the RC.jl default. Requires aseedfor reproducibility."irrational"— deterministic: an entry is negated when the corresponding decimal digit of pi (offset bystart) is odd (RC.jlirrational_sample!). Fully reproducible, no RNG."regular"— deterministic: everystrides-th entry (in flat column-major order) is negated (RC.jl_regular_sample!)."none"— leave every sign positive (RC.jlno_sample).
| PARAMETER | DESCRIPTION |
|---|---|
weight
|
The single magnitude assigned to every input weight (RC.jl
TYPE:
|
sign_rule
|
The sign-assignment rule (RC.jl
TYPE:
|
positive_prob
|
Probability an entry stays positive under
TYPE:
|
start
|
First pi-digit offset under
TYPE:
|
strides
|
Stride under
TYPE:
|
input_scaling
|
Uniform magnitude knob from the shared scaling contract (see
TYPE:
|
seed
|
Reproducibility seed for the
TYPE:
|
References
A. Rodan and P. Tiňo, "Minimum Complexity Echo State Network," IEEE Trans. Neural Netw., vol. 22, no. 1, pp. 131-144, Jan. 2011.
ReservoirComputing.jl minimal_init (src/inits/inits_input.jl).
Examples:
>>> from resdag.init.input_feedback import MinimalInputInitializer
>>>
>>> # Deterministic pi-digit signs, magnitude 0.1
>>> init = MinimalInputInitializer(weight=0.1, sign_rule="irrational")
>>> weight = torch.empty(8, 3)
>>> init.initialize(weight) # dense {-0.1, +0.1} matrix
Source code in src/resdag/init/input_feedback/minimal.py
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 | |
initialize
¶
Initialize a dense constant-magnitude weight with signed entries.
| PARAMETER | DESCRIPTION |
|---|---|
weight
|
Weight tensor of shape
TYPE:
|
**kwargs
|
Per-call keyword overrides. A recognized
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The initialized weight tensor (modified in-place). |
Source code in src/resdag/init/input_feedback/minimal.py
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 | |
BernoulliInputInitializer
¶
BernoulliInputInitializer(
p: float = 0.5,
connectivity: float | None = None,
input_scaling: float | None = None,
seed: SeedLike = None,
)
Bases: InputFeedbackInitializer
Bernoulli sign initializer for input/feedback weight matrices.
Each entry is +1 with probability p and -1 otherwise — the
canonical sparse-sign input matrix of the reservoir-computing literature.
Combined with connectivity (the single most common input-matrix recipe:
a fixed density of random ±1 signs per channel) and the shared
input_scaling magnitude knob.
This is the migration target for reservoirpy's
reservoirpy.mat_gen.bernoulli: p matches its p (the
probability of drawing +1), and connectivity matches its
connectivity density argument.
| PARAMETER | DESCRIPTION |
|---|---|
p
|
Probability that an entry is
TYPE:
|
connectivity
|
Density knob from the shared scaling contract (see
TYPE:
|
input_scaling
|
Uniform magnitude knob from the shared scaling contract.
TYPE:
|
seed
|
Reproducibility seed for the Bernoulli draw and the connectivity mask.
Accepts a plain
TYPE:
|
Notes
The produced matrix is a pure function of (p, connectivity, input_scaling, seed, shape, device): repeated calls on the same instance with equal
shapes on the same device yield identical matrices. Pass seed=None for a
draw tied to torch's global RNG (reproducible under torch.manual_seed).
Examples:
>>> from resdag.init.input_feedback import BernoulliInputInitializer
>>>
>>> # 10%-sparse balanced ±1 input matrix (a classic sparse input recipe).
>>> init = BernoulliInputInitializer(connectivity=0.1, seed=42)
>>> weight = torch.empty(100, 10) # (reservoir_size, feedback_size)
>>> init.initialize(weight)
>>>
>>> # Use in ESNLayer.
>>> from resdag.layers import ESNLayer
>>> reservoir = ESNLayer(
... reservoir_size=100,
... feedback_size=10,
... feedback_initializer=init,
... )
Source code in src/resdag/init/input_feedback/bernoulli.py
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 | |
initialize
¶
Initialize weight with Bernoulli ±1 entries.
| PARAMETER | DESCRIPTION |
|---|---|
weight
|
Weight tensor of shape
TYPE:
|
**kwargs
|
Per-call keyword overrides. Recognized
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The initialized weight tensor (same object, modified in-place). |
Source code in src/resdag/init/input_feedback/bernoulli.py
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 | |
BinaryBalancedInitializer
¶
BinaryBalancedInitializer(
input_scaling: float | None = None,
balance_global: bool = True,
step: int | None = None,
seed: int | None = None,
)
Bases: InputFeedbackInitializer
Deterministic binary balanced initializer using Walsh-Hadamard structure.
Generates a dense input matrix with entries in {-1, +1}, column-wise balance (sum close to zero), and low inter-column correlation via truncated Walsh-Hadamard structure.
The matrix is built without randomness (deterministic) and is suitable for ESN/RC setups where each column (reservoir unit) should receive a balanced mix of positive/negative signs from the input channels, and columns should be nearly orthogonal.
| PARAMETER | DESCRIPTION |
|---|---|
input_scaling
|
Uniform magnitude knob from the shared scaling contract (see
TYPE:
|
balance_global
|
When rows is odd, enforce near-equal global count of +1 vs -1 column-sums by flipping full columns.
TYPE:
|
step
|
Preferred column selection step. If None or not coprime with L, the initializer will choose the smallest odd step that is coprime with L.
TYPE:
|
seed
|
Unused (kept for API compatibility). The initializer is fully deterministic.
TYPE:
|
Notes
- Column-wise balance: sum over rows per column is exactly 0 if rows even, else ±1.
- Low correlation: columns originate from orthogonal Hadamard columns.
- Deterministic: no RNG is used; the output is reproducible given the shape.
Examples:
>>> from resdag.init.input_feedback import BinaryBalancedInitializer
>>>
>>> init = BinaryBalancedInitializer(input_scaling=0.5, balance_global=True)
>>> weight = torch.empty(100, 10) # (reservoir_size, input_dim)
>>> init.initialize(weight)
>>>
>>> # Each column will have sum close to 0 (balanced)
>>> column_sums = weight.sum(dim=0)
>>> print(column_sums) # Close to zero
Source code in src/resdag/init/input_feedback/binary_balanced.py
64 65 66 67 68 69 70 71 72 73 74 | |
initialize
¶
Initialize weight tensor with binary balanced structure.
| PARAMETER | DESCRIPTION |
|---|---|
weight
|
Weight tensor of shape (out_features, in_features)
TYPE:
|
**kwargs
|
Per-call keyword overrides. A recognized
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Initialized weight tensor |
Source code in src/resdag/init/input_feedback/binary_balanced.py
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 | |
ChainOfNeuronsInputInitializer
¶
ChainOfNeuronsInputInitializer(
features: int | None = None, weights: float | Sequence[float] = 1.0
)
Bases: InputFeedbackInitializer
Input initializer for chain-of-neurons reservoirs.
For reservoirs organized as multiple parallel chains, this initializer connects each input to the first neuron of its corresponding chain.
| PARAMETER | DESCRIPTION |
|---|---|
features
|
Number of chains. Must equal the number of inputs (the weight's
TYPE:
|
weights
|
Either a single float (same weight for all input→chain pairs) or a sequence of floats (one weight per input/chain). |
Examples:
>>> from resdag.init.input_feedback import ChainOfNeuronsInputInitializer
>>>
>>> # Infer the number of chains from the weight (3 columns -> 3 chains)
>>> init = ChainOfNeuronsInputInitializer(weights=1.0)
>>> weight = torch.empty(150, 3) # (reservoir_size, num_inputs)
>>> init.initialize(weight)
>>>
>>> # Or pin it explicitly (validated against the weight shape)
>>> init = ChainOfNeuronsInputInitializer(features=3, weights=1.0)
>>>
>>> # Each input connects only to the first neuron of its chain
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Source code in src/resdag/init/input_feedback/chain_of_neurons_input.py
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | |
initialize
¶
Initialize weight tensor for chain-of-neurons topology.
| PARAMETER | DESCRIPTION |
|---|---|
weight
|
Weight tensor of shape (out_features, in_features)
out_features = reservoir_size (units)
in_features = num_inputs (must equal features; when
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Initialized weight tensor |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If an explicit |
Source code in src/resdag/init/input_feedback/chain_of_neurons_input.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 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 | |
ChebyshevInitializer
¶
ChebyshevInitializer(
p: float = 0.3, q: float = 5.9, k: float = 3.8, input_scaling: float | None = None
)
Bases: InputFeedbackInitializer
Chebyshev mapping initializer for deterministic chaotic initialization.
This initializer constructs a weight matrix based on the Chebyshev polynomial map, ensuring structured, chaotic initialization while maintaining a controlled range.
The Chebyshev polynomial recurrence exhibits deterministic chaos, making it a structured alternative to purely random weight initialization. This enhances the richness of how the input signal is connected to the reservoir neurons.
The Chebyshev map is applied column-wise: - First column: W[:, 0] = p * sin((i / (rows+1)) * (π / q)) - Subsequent columns: W[:, j] = cos(k * arccos(W[:, j-1]))
where k controls chaotic behavior (optimal range: 2 < k < 4).
The seed column (column 0) lives on the small amplitude [-p, p] while the
chaotic columns span [-1, 1], so the raw map systematically de-weights the
first feedback dimension (its max|W| is ~p against ~1 elsewhere).
To honor the shared scaling contract — whose magnitude statistic is max|W|
per column for this elementwise initializer — each column is normalized to unit
peak amplitude (divided by its own max|W|) before input_scaling applies.
Every column then peaks at the same input_scaling (or 1 when
input_scaling is None), and the 1D-feedback matrix peaks at input_scaling
rather than the unscaled seed amplitude p.
| PARAMETER | DESCRIPTION |
|---|---|
p
|
Scaling factor for the initial sinusoidal weights. Should be in (0, 1).
TYPE:
|
q
|
Parameter controlling the initial sinusoidal distribution.
TYPE:
|
k
|
Control parameter of the Chebyshev map. Must be in (2, 4) for chaotic behavior.
TYPE:
|
input_scaling
|
Uniform magnitude knob from the shared scaling contract (see
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If k is not in the valid range (2, 4). |
References
M. Xie, Q. Wang, and S. Yu, "Time Series Prediction of ESN Based on Chebyshev Mapping and Strongly Connected Topology," Neural Process Lett, vol. 56, no. 1, p. 30, Feb. 2024.
Examples:
>>> from resdag.init.input_feedback import ChebyshevInitializer
>>>
>>> init = ChebyshevInitializer(p=0.3, k=3.5, input_scaling=0.8)
>>> weight = torch.empty(100, 10)
>>> init.initialize(weight)
Source code in src/resdag/init/input_feedback/chebyshev.py
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 | |
initialize
¶
Initialize weight tensor using Chebyshev mapping.
| PARAMETER | DESCRIPTION |
|---|---|
weight
|
Weight tensor of shape (out_features, in_features)
TYPE:
|
**kwargs
|
Per-call keyword overrides. A recognized
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Initialized weight tensor with Chebyshev structure |
Source code in src/resdag/init/input_feedback/chebyshev.py
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 | |
ChessboardInitializer
¶
ChessboardInitializer(input_scaling: float | None = None)
Bases: InputFeedbackInitializer
Chessboard pattern initializer with alternating {-1, +1} values.
Creates a deterministic checkerboard pattern where adjacent elements alternate in sign. This creates a structured, high-frequency pattern that can be useful for certain reservoir dynamics.
The pattern is: W[i, j] = (-1)^(i+j)
| PARAMETER | DESCRIPTION |
|---|---|
input_scaling
|
Uniform magnitude knob from the shared scaling contract (see
TYPE:
|
Examples:
>>> from resdag.init.input_feedback import ChessboardInitializer
>>>
>>> init = ChessboardInitializer(input_scaling=0.5)
>>> weight = torch.empty(5, 10)
>>> init.initialize(weight)
>>>
>>> # Creates alternating pattern:
>>> # [[ 0.5, -0.5, 0.5, -0.5, ...],
>>> # [-0.5, 0.5, -0.5, 0.5, ...],
>>> # [ 0.5, -0.5, 0.5, -0.5, ...],
>>> # ...]
Source code in src/resdag/init/input_feedback/chessboard.py
46 47 48 | |
initialize
¶
Initialize weight tensor with chessboard pattern.
| PARAMETER | DESCRIPTION |
|---|---|
weight
|
Weight tensor of shape (out_features, in_features)
TYPE:
|
**kwargs
|
Per-call keyword overrides. A recognized
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Initialized weight tensor with chessboard pattern |
Source code in src/resdag/init/input_feedback/chessboard.py
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 | |
DendrocycleInputInitializer
¶
DendrocycleInputInitializer(
c: float | None = None,
C: int | None = None,
draw_width: float = 1.0,
input_scaling: float | None = None,
connectivity: float | None = None,
seed: int | None = None,
)
Bases: InputFeedbackInitializer
Input initializer for dendro-cycle reservoirs.
Generates a matrix where only the core (cycle) nodes receive input connections. All other entries are zero. This is specific to dendrocycle topologies where inputs should only connect to the core ring.
Each active connection draws a weight from U[-draw_width, draw_width] and
is then scaled by the shared input_scaling contract. draw_width is the
draw half-width (the spread of the raw distribution); input_scaling is the
uniform final magnitude knob shared by every initializer. With
input_scaling=0.5 every drawn weight is halved, so max|W| scales
linearly with input_scaling (max|W| <= draw_width * input_scaling).
Note.
Prior to the unified scaling contract, input_scaling here meant the
draw half-width (defaulting to 1.0). That role is now draw_width;
input_scaling is the uniform multiplicative transform shared with every
other initializer and defaults to None (no scaling). To reproduce the
old DendrocycleInputInitializer(input_scaling=s) draw, pass
draw_width=s.
| PARAMETER | DESCRIPTION |
|---|---|
c
|
Fraction of nodes forming the cycle (0 < c <= 1). Provide either c or C.
TYPE:
|
C
|
Number of cycle (core) nodes. If provided, c is ignored.
TYPE:
|
draw_width
|
Half-width of the uniform draw
TYPE:
|
input_scaling
|
Uniform multiplicative scaling applied as the final transform.
TYPE:
|
connectivity
|
Unused by this initializer: dendrocycle defines its own (core-only)
connectivity pattern, so this knob is accepted for API uniformity but
ignored. Always
TYPE:
|
seed
|
Random seed for reproducibility.
TYPE:
|
Examples:
>>> from resdag.init.input_feedback import DendrocycleInputInitializer
>>>
>>> # Initialize for dendrocycle with 20% core nodes, weights in U[-0.5, 0.5]
>>> init = DendrocycleInputInitializer(c=0.2, draw_width=0.5, seed=42)
>>> weight = torch.empty(100, 8) # (reservoir_size, num_inputs)
>>> init.initialize(weight)
>>>
>>> # Only first 20 neurons (core) have non-zero weights
Source code in src/resdag/init/input_feedback/dendrocycle_input.py
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | |
initialize
¶
Initialize weight tensor for dendrocycle topology.
The RNG is constructed from self.seed on every call, so the produced
matrix is a pure function of (seed, shape). Repeated calls on the
same instance with equal shapes therefore yield identical matrices.
Pass seed=None for a fresh draw on each call.
| PARAMETER | DESCRIPTION |
|---|---|
weight
|
Weight tensor of shape (out_features, in_features) out_features = reservoir_size (N) in_features = num_inputs (M)
TYPE:
|
**kwargs
|
Per-call keyword overrides. A recognized
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Initialized weight tensor (only core nodes have non-zero weights) |
Source code in src/resdag/init/input_feedback/dendrocycle_input.py
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 | |
NormalInputInitializer
¶
NormalInputInitializer(
loc: float = 0.0,
scale: float = 1.0,
connectivity: float | None = None,
input_scaling: float | None = None,
seed: SeedLike = None,
)
Bases: InputFeedbackInitializer
Gaussian (normal) initializer for input/feedback weight matrices.
Draws every entry independently from Normal(loc, scale) — the
bread-and-butter dense Gaussian input matrix of the reservoir-computing
literature. Optionally sparsified per input channel via connectivity and
scaled uniformly via the shared input_scaling contract.
This is the migration target for reservoirpy's
reservoirpy.mat_gen.normal (and the "normal" distribution of
reservoirpy.mat_gen.random_sparse).
| PARAMETER | DESCRIPTION |
|---|---|
loc
|
Mean of the Gaussian draw. Defaults to
TYPE:
|
scale
|
Standard deviation of the Gaussian draw (must be non-negative). Defaults
to
TYPE:
|
connectivity
|
Density knob from the shared scaling contract (see
TYPE:
|
input_scaling
|
Uniform magnitude knob from the shared scaling contract.
TYPE:
|
seed
|
Reproducibility seed for the Gaussian draw and the connectivity mask.
Accepts a plain
TYPE:
|
Notes
The produced matrix is a pure function of (loc, scale, connectivity, input_scaling, seed, shape, device): repeated calls on the same instance
with equal shapes on the same device yield identical matrices. Pass
seed=None for a draw tied to torch's global RNG (reproducible under
torch.manual_seed).
Examples:
>>> from resdag.init.input_feedback import NormalInputInitializer
>>>
>>> # 10%-sparse standard-normal input matrix.
>>> init = NormalInputInitializer(connectivity=0.1, seed=42)
>>> weight = torch.empty(100, 10) # (reservoir_size, feedback_size)
>>> init.initialize(weight)
>>>
>>> # Use in ESNLayer.
>>> from resdag.layers import ESNLayer
>>> reservoir = ESNLayer(
... reservoir_size=100,
... feedback_size=10,
... feedback_initializer=init,
... )
Source code in src/resdag/init/input_feedback/normal.py
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 | |
initialize
¶
Initialize weight with Normal(loc, scale) entries.
| PARAMETER | DESCRIPTION |
|---|---|
weight
|
Weight tensor of shape
TYPE:
|
**kwargs
|
Per-call keyword overrides. Recognized
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The initialized weight tensor (same object, modified in-place). |
Source code in src/resdag/init/input_feedback/normal.py
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 | |
OppositeAnchorsInitializer
¶
Bases: InputFeedbackInitializer
Initializer that connects each input to two opposite anchors on an n-node ring.
Each input channel connects to two anchor nodes on opposite sides of the ring,
with equal-magnitude bipolar weights on both anchors (input_scaling normalized
by sqrt(2), so the per-channel L2 norm equals input_scaling). If the two
anchors coincide (n=1), all weight goes to that single node.
The first (positive) anchor of channel i is placed at round(i * n / m) % n,
spreading the m anchors evenly around the full ring; the second (negative)
anchor is the diametrically opposite node (anchor + n // 2) % n. Spreading over
the full ring (rather than a semicircle) keeps the columns distinct for any
in_features <= reservoir_size, so W_in/W_fb stays full column rank.
This is useful for ring/cycle topologies where you want inputs distributed evenly around the ring with bipolar activation patterns.
Scaling
For this structured initializer the magnitude statistic governed by the shared
contract is the per-channel L2 norm, which equals input_scaling. Hence
input_scaling=0.5 makes every channel's column have L2 norm 0.5 (and,
since each column is two equal-magnitude bipolar entries, max|W| = 0.5/sqrt(2)).
The per-channel L2 norm therefore scales linearly with input_scaling.
Capacity limit
The ring has only n = reservoir_size nodes, so at most n channels can be
assigned distinct anchors. initialize raises ValueError when
in_features > reservoir_size (more channels than nodes), since duplicate
columns would be unavoidable.
| PARAMETER | DESCRIPTION |
|---|---|
input_scaling
|
Per-channel L2 norm of each input column. Defaults to
TYPE:
|
gain
|
Deprecated alias for
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the resolved scaling is not a positive finite float (at construction),
if both |
Examples:
>>> from resdag.init.input_feedback import OppositeAnchorsInitializer
>>>
>>> init = OppositeAnchorsInitializer(input_scaling=1.0)
>>> weight = torch.empty(100, 5) # (reservoir_size, num_inputs)
>>> init.initialize(weight)
>>>
>>> # Each input connects to two opposite points on the ring
Source code in src/resdag/init/input_feedback/opposite_anchors.py
77 78 79 80 81 82 83 84 85 86 | |
initialize
¶
Initialize weight tensor with opposite anchor pattern.
| PARAMETER | DESCRIPTION |
|---|---|
weight
|
Weight tensor of shape (out_features, in_features) out_features = number of ring nodes (n) in_features = number of input channels (m)
TYPE:
|
**kwargs
|
Per-call keyword overrides. A recognized
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Initialized weight tensor |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Source code in src/resdag/init/input_feedback/opposite_anchors.py
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 | |
PseudoDiagonalInitializer
¶
PseudoDiagonalInitializer(
input_scaling: float | None = None, binarize: bool = False, seed: int | None = None
)
Bases: InputFeedbackInitializer
Pseudo-diagonal initializer for structured input connections.
This initializer creates a structured input weight matrix where each input dimension connects to a contiguous block of reservoir neurons. This creates a "pseudo-diagonal" pattern that can improve input-to-reservoir mapping, especially when input dimensions have semantic meaning.
The connectivity pattern ensures:
- Each reservoir neuron receives input from exactly one input dimension
- Each input dimension connects to approximately N/D reservoir neurons (where N=reservoir size, D=input dimension)
- Connections form contiguous blocks (not random)
| PARAMETER | DESCRIPTION |
|---|---|
input_scaling
|
Uniform magnitude knob from the shared scaling contract (see
TYPE:
|
binarize
|
Whether to binarize weights to {-input_scaling, input_scaling} instead of uniform distribution.
TYPE:
|
seed
|
Random seed for reproducibility.
TYPE:
|
Examples:
>>> from resdag.init.input_feedback import PseudoDiagonalInitializer
>>>
>>> init = PseudoDiagonalInitializer(input_scaling=1.0, binarize=False, seed=42)
>>> weight = torch.empty(200, 5) # (reservoir_size, input_dim)
>>> init.initialize(weight)
>>>
>>> # Each of the 5 inputs connects to a contiguous block of ~40 neurons
Source code in src/resdag/init/input_feedback/pseudo_diagonal.py
55 56 57 58 59 60 61 62 63 | |
initialize
¶
Initialize weight tensor with pseudo-diagonal structure.
The RNG is constructed from self.seed on every call, so the produced
matrix is a pure function of (seed, shape). Repeated calls on the
same instance with equal shapes therefore yield identical matrices.
Pass seed=None for a fresh draw on each call.
| PARAMETER | DESCRIPTION |
|---|---|
weight
|
Weight tensor of shape (out_features, in_features)
TYPE:
|
**kwargs
|
Per-call keyword overrides. A recognized
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Initialized weight tensor with block structure |
Source code in src/resdag/init/input_feedback/pseudo_diagonal.py
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 | |
RandomBinaryInitializer
¶
Bases: InputFeedbackInitializer
Binary random initializer for input/feedback weight matrices.
This initializer creates binary weight matrices with values in {-1, +1}. Each weight is randomly chosen to be either -1 or +1, optionally scaled.
Binary weights can be advantageous for: - Memory efficiency (can be stored as bits) - Computational efficiency (multiplication becomes addition/subtraction) - Improved robustness in some cases - Easier interpretation
| PARAMETER | DESCRIPTION |
|---|---|
input_scaling
|
Uniform magnitude knob from the shared scaling contract (see
TYPE:
|
seed
|
Reproducibility seed for the binary draw. Accepts a plain
TYPE:
|
Examples:
>>> from resdag.init.input_feedback import RandomBinaryInitializer
>>>
>>> # Create binary initializer
>>> init = RandomBinaryInitializer(input_scaling=0.5, seed=42)
>>>
>>> # Initialize weights
>>> weight = torch.empty(100, 10)
>>> init.initialize(weight)
>>>
>>> # All values will be either -0.5 or +0.5
>>> unique_values = torch.unique(weight)
>>> print(unique_values) # tensor([-0.5, 0.5])
Source code in src/resdag/init/input_feedback/random_binary.py
58 59 60 61 62 63 64 | |
initialize
¶
Initialize weight tensor with binary random values.
The draw uses a torch.Generator built from self.seed on the
target weight's device (no CPU build + copy), so the produced matrix
is a pure function of (seed, shape, device). Repeated calls on the
same instance with equal shapes on the same device therefore yield
identical matrices. Pass seed=None for a draw tied to torch's global
RNG (reproducible under torch.manual_seed).
| PARAMETER | DESCRIPTION |
|---|---|
weight
|
Weight tensor of shape (out_features, in_features)
TYPE:
|
**kwargs
|
Per-call keyword overrides. A recognized
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Initialized weight tensor with binary values |
Source code in src/resdag/init/input_feedback/random_binary.py
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 | |
RandomInputInitializer
¶
Bases: InputFeedbackInitializer
Random initializer for feedback/input weight matrices.
This initializer creates random weight matrices connecting inputs (feedback or external) to reservoir neurons. Values are sampled uniformly from [-1, 1] and optionally scaled by an input scaling factor.
This is a simple, commonly used initializer for input connections. It provides random, unstructured connectivity from inputs to the reservoir.
| PARAMETER | DESCRIPTION |
|---|---|
input_scaling
|
Uniform magnitude knob from the shared scaling contract (see
TYPE:
|
seed
|
Reproducibility seed for the uniform draw. Accepts a plain
TYPE:
|
Notes
Input Scaling:
The input_scaling parameter controls how strongly input signals affect the reservoir: - Low scaling (0.1-0.5): Weak input influence, reservoir dynamics dominate - Moderate scaling (0.5-1.0): Balanced input and reservoir dynamics - High scaling (1.0-5.0): Strong input influence, input-driven dynamics
Usage:
This initializer is typically used for: - Feedback weights: How feedback signals enter the reservoir - Input weights: How external inputs enter the reservoir (if used)
Best Practices:
- Start with input_scaling=1.0 and tune based on performance
- Lower scaling often works better for chaotic systems
- Higher scaling can help when inputs are weak or noisy
- Use seed for reproducibility
Examples:
>>> from resdag.init.input_feedback import RandomInputInitializer
>>>
>>> # Create initializer
>>> init = RandomInputInitializer(input_scaling=1.0, seed=42)
>>>
>>> # Initialize a weight tensor
>>> weight = torch.empty(100, 10) # (reservoir_size, feedback_size)
>>> init.initialize(weight)
>>>
>>> # Use in ESNLayer
>>> reservoir = ESNLayer(
... reservoir_size=100,
... feedback_size=10,
... feedback_initializer=init
... )
Source code in src/resdag/init/input_feedback/random.py
85 86 87 88 89 90 91 | |
initialize
¶
Initialize weight tensor with uniform random values.
The draw uses a torch.Generator built from self.seed on the
target weight's device (no CPU build + copy), so the produced matrix
is a pure function of (seed, shape, device). Repeated calls on the
same instance with equal shapes on the same device therefore yield
identical matrices. Pass seed=None for a draw tied to torch's global
RNG (reproducible under torch.manual_seed).
| PARAMETER | DESCRIPTION |
|---|---|
weight
|
Weight tensor of shape (out_features, in_features)
TYPE:
|
**kwargs
|
Per-call keyword overrides. A recognized
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Initialized weight tensor |
Source code in src/resdag/init/input_feedback/random.py
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 | |
RingWindowInputInitializer
¶
RingWindowInputInitializer(
c: float,
window: int | float,
taper: str = "flat",
signed: str = "allpos",
input_scaling: float | None = None,
gain: float | None = None,
)
Bases: InputFeedbackInitializer
Deterministic windowed input initializer for ring-based topologies.
Feeds each input channel into a contiguous window on the core ring of a dendrocycle(+chords) reservoir. Only the first C = round(c * n) columns (core) receive nonzeros.
Scaling
For this structured initializer the magnitude statistic governed by the shared
contract is the per-channel L2 norm, which equals input_scaling: each
channel's window vector is renormalized so its L2 norm is exactly
input_scaling. Hence input_scaling=0.5 makes every channel's column have
L2 norm 0.5; the per-channel L2 norm scales linearly with input_scaling.
| PARAMETER | DESCRIPTION |
|---|---|
c
|
Fraction of core ring nodes. First round(c*n) columns are core.
TYPE:
|
window
|
If int >= 1: number of core nodes per channel window. If float in (0, 1]: fraction of C per channel window (rounded >= 1). |
taper
|
Weight profile within a channel's window centered on its center index.
TYPE:
|
signed
|
Sign policy for weights.
TYPE:
|
input_scaling
|
Per-channel L2-norm after taper/sign are applied. Defaults to
TYPE:
|
gain
|
Deprecated alias for
TYPE:
|
Examples:
>>> from resdag.init.input_feedback import RingWindowInputInitializer
>>>
>>> init = RingWindowInputInitializer(
... c=0.5, window=10, taper="cosine", signed="alt_ring", input_scaling=1.0
... )
>>> weight = torch.empty(100, 5) # (reservoir_size, num_inputs)
>>> init.initialize(weight)
>>>
>>> # Each input connects to a windowed region of the core ring
Source code in src/resdag/init/input_feedback/ring_window.py
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 | |
initialize
¶
Initialize weight tensor with ring window pattern.
| PARAMETER | DESCRIPTION |
|---|---|
weight
|
Weight tensor of shape (out_features, in_features) out_features = reservoir_size (n) in_features = num_inputs (m)
TYPE:
|
**kwargs
|
Per-call keyword overrides. A recognized
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Initialized weight tensor |
Source code in src/resdag/init/input_feedback/ring_window.py
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 | |
UniformInputInitializer
¶
UniformInputInitializer(
low: float = -1.0,
high: float = 1.0,
connectivity: float | None = None,
input_scaling: float | None = None,
seed: SeedLike = None,
)
Bases: InputFeedbackInitializer
Bounded uniform initializer for input/feedback weight matrices.
Draws every entry independently from Uniform(low, high). Unlike the
baseline random initializer (fixed [-1, 1]), the bounds are
configurable, so asymmetric or narrow ranges are expressible directly.
Optionally sparsified per input channel via connectivity and scaled
uniformly via the shared input_scaling contract.
This is the migration target for reservoirpy's
reservoirpy.mat_gen.uniform (and the "uniform" distribution of
reservoirpy.mat_gen.random_sparse).
| PARAMETER | DESCRIPTION |
|---|---|
low
|
Inclusive lower bound of the uniform draw. Defaults to
TYPE:
|
high
|
Exclusive upper bound of the uniform draw. Defaults to
TYPE:
|
connectivity
|
Density knob from the shared scaling contract (see
TYPE:
|
input_scaling
|
Uniform magnitude knob from the shared scaling contract.
TYPE:
|
seed
|
Reproducibility seed for the uniform draw and the connectivity mask.
Accepts a plain
TYPE:
|
Notes
The produced matrix is a pure function of (low, high, connectivity, input_scaling, seed, shape, device): repeated calls on the same instance
with equal shapes on the same device yield identical matrices. Pass
seed=None for a draw tied to torch's global RNG (reproducible under
torch.manual_seed).
Examples:
>>> from resdag.init.input_feedback import UniformInputInitializer
>>>
>>> # A narrow, asymmetric uniform input matrix.
>>> init = UniformInputInitializer(low=0.0, high=0.5, seed=42)
>>> weight = torch.empty(100, 10) # (reservoir_size, feedback_size)
>>> init.initialize(weight)
>>>
>>> # Use in ESNLayer.
>>> from resdag.layers import ESNLayer
>>> reservoir = ESNLayer(
... reservoir_size=100,
... feedback_size=10,
... feedback_initializer=init,
... )
Source code in src/resdag/init/input_feedback/uniform.py
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 | |
initialize
¶
Initialize weight with Uniform(low, high) entries.
| PARAMETER | DESCRIPTION |
|---|---|
weight
|
Weight tensor of shape
TYPE:
|
**kwargs
|
Per-call keyword overrides. Recognized
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The initialized weight tensor (same object, modified in-place). |
Source code in src/resdag/init/input_feedback/uniform.py
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 | |
WeightedInputInitializer
¶
Bases: InputFeedbackInitializer
Weighted block-diagonal random input layer (RC.jl weighted_init [Lu2017]).
Each of the in_size input channels connects to a disjoint contiguous
block of q = floor(reservoir_size / in_size) reservoir units. Block
values are drawn uniformly from [-input_scaling, input_scaling]; every
off-block entry is zero. Any trailing reservoir_size - q * in_size rows
are left unconnected (all-zero), matching RC.jl's unconnected tail (RC.jl
resizes the matrix instead; resdag keeps the requested shape — see the module
docstring).
This differs from PseudoDiagonalInitializer only in the block
sizing: weighted_init gives every channel exactly q units (leaving
a zero tail when reservoir_size is not a multiple of in_size), while
pseudo_diagonal distributes the remainder so every unit is connected.
| PARAMETER | DESCRIPTION |
|---|---|
input_scaling
|
Half-width of the uniform block draw: nonzero entries are sampled from
TYPE:
|
seed
|
Reproducibility seed for the uniform block draws.
TYPE:
|
References
Z. Lu et al., "Reservoir observers: Model-free inference of unmeasured variables in chaotic systems," Chaos, vol. 27, no. 4, 041102, 2017.
ReservoirComputing.jl weighted_init (src/inits/inits_input.jl).
Examples:
>>> from resdag.init.input_feedback import WeightedInputInitializer
>>>
>>> init = WeightedInputInitializer(input_scaling=0.1, seed=42)
>>> weight = torch.empty(9, 3) # 3 blocks of q=3 units each
>>> init.initialize(weight)
Source code in src/resdag/init/input_feedback/weighted.py
81 82 83 84 85 86 87 | |
initialize
¶
Fill a block-diagonal weight with uniform block values.
| PARAMETER | DESCRIPTION |
|---|---|
weight
|
Weight tensor of shape
TYPE:
|
**kwargs
|
Per-call keyword overrides. A recognized
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The initialized weight tensor (modified in-place). |
Source code in src/resdag/init/input_feedback/weighted.py
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 | |
WeightedMinimalInitializer
¶
WeightedMinimalInitializer(
weight: float = 0.1,
sign_rule: str = "none",
positive_prob: float = 0.5,
start: int = 1,
strides: int = 2,
input_scaling: float | None = None,
seed: int | None = None,
)
Bases: InputFeedbackInitializer
Minimal weighted block-diagonal input layer (RC.jl weighted_minimal).
The deterministic-magnitude sibling of WeightedInputInitializer:
each input channel connects to a disjoint block of q = floor(reservoir_size / in_size) reservoir units, but every nonzero entry has the same
magnitude weight (the minimal-complexity construction of Rodan & Tiňo,
applied to the weighted block wiring inspired by Lu et al. 2017). Only the
signs vary, chosen by sign_rule.
The trailing reservoir_size - q * in_size rows are left unconnected
(all-zero), matching RC.jl's unconnected tail (RC.jl resizes instead; resdag
keeps the requested shape — see the module docstring).
Sign rules (RC.jl sampling_type) are applied over the full
(reservoir_size, in_size) matrix in RC.jl's column-major traversal order,
exactly as RC.jl runs the sampler after building the block matrix; off-block
zeros are unaffected by a sign flip. See
resdag.init.input_feedback.MinimalInputInitializer for the rule
definitions.
| PARAMETER | DESCRIPTION |
|---|---|
weight
|
The single magnitude for every nonzero block entry (RC.jl
TYPE:
|
sign_rule
|
Sign-assignment rule (RC.jl
TYPE:
|
positive_prob
|
Probability an entry stays positive under
TYPE:
|
start
|
First pi-digit offset under
TYPE:
|
strides
|
Stride under
TYPE:
|
input_scaling
|
Uniform magnitude knob from the shared scaling contract.
TYPE:
|
seed
|
Reproducibility seed for the
TYPE:
|
References
A. Rodan and P. Tiňo, "Minimum Complexity Echo State Network," IEEE Trans. Neural Netw., vol. 22, no. 1, pp. 131-144, Jan. 2011.
Z. Lu et al., "Reservoir observers," Chaos, vol. 27, no. 4, 041102, 2017.
ReservoirComputing.jl weighted_minimal (src/inits/inits_input.jl).
Examples:
>>> from resdag.init.input_feedback import WeightedMinimalInitializer
>>>
>>> init = WeightedMinimalInitializer(weight=0.99)
>>> weight = torch.empty(9, 3) # 3 blocks of q=3 units, all +0.99
>>> init.initialize(weight)
Source code in src/resdag/init/input_feedback/weighted.py
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 | |
initialize
¶
Fill a block-diagonal weight with constant-magnitude signed entries.
| PARAMETER | DESCRIPTION |
|---|---|
weight
|
Weight tensor of shape
TYPE:
|
**kwargs
|
Per-call keyword overrides. A recognized
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The initialized weight tensor (modified in-place). |
Source code in src/resdag/init/input_feedback/weighted.py
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 | |
ZeroInitializer
¶
ZeroInitializer()
Bases: InputFeedbackInitializer
Initializer that sets all weights to zero.
Source code in src/resdag/init/input_feedback/zero.py
13 14 15 | |
initialize
¶
Initialize weight tensor with zero values.
Source code in src/resdag/init/input_feedback/zero.py
17 18 19 20 21 | |
get_input_feedback
¶
get_input_feedback(name: str, **override_kwargs: Any) -> InputFeedbackInitializer
Get a pre-configured input/feedback initializer by name.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
Name of the initializer (e.g., "random", "binary_balanced")
TYPE:
|
**override_kwargs
|
Keyword arguments to override default initializer parameters
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
InputFeedbackInitializer
|
Initializer instance |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If initializer name is not registered |
Examples:
>>> initializer = get_input_feedback("binary_balanced", input_scaling=0.5)
>>> weight = torch.empty(100, 10)
>>> initializer.initialize(weight)
Source code in src/resdag/init/input_feedback/registry.py
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 | |
register_input_feedback
¶
Decorator to register an input/feedback initializer.
Registers either an InputFeedbackInitializer subclass or a
plain matrix-building function in the registry at definition time,
making it available by name to ESNLayer and other components.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
Name for the initializer (must be unique)
TYPE:
|
**default_kwargs
|
Default keyword arguments for the initializer constructor (classes) or for the function call (plain functions)
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
callable
|
Decorator function |
Examples:
Registering a class:
>>> @register_input_feedback("my_init", scaling=0.5)
... class MyInitializer(InputFeedbackInitializer):
... def __init__(self, scaling=1.0):
... self.scaling = scaling
...
... def initialize(self, weight, **kwargs):
... # ... initialization logic
... return weight
Registering a plain function (build style — return the matrix):
>>> @register_input_feedback("first_neuron", scale=1.0)
... def first_neuron(rows, cols, scale=1.0):
... w = torch.zeros(rows, cols)
... w[0, :] = scale
... return w
Notes
- Classes must inherit from
InputFeedbackInitializerand implementinitialize(weight, **kwargs). - Functions follow the
FunctionInitializerconventions:fn(rows, cols, **kwargs) -> matrixor in-placefn(tensor, **kwargs). - Registered initializers can be accessed via
get_input_feedback(name).
Source code in src/resdag/init/input_feedback/registry.py
22 23 24 25 26 27 28 29 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 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 | |
show_input_initializers
¶
Show available input/feedback initializers or details for a specific one.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
Name of initializer to inspect. If None, prints all initializers and returns them as a list.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list of str or None
|
When |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the specified initializer name is not registered. |
Examples:
>>> show_input_initializers()
['binary_balanced', 'chebyshev', 'chessboard', ...]
Source code in src/resdag/init/input_feedback/registry.py
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 | |
Direct matrix builders¶
matrices
¶
Matrix-Builder Topologies¶
Direct matrix-construction functions registered as topologies — the
non-graph counterpart of resdag.init.graphs. Each function takes the
matrix size n first, returns an (n, n) matrix, and is registered via
resdag.init.topology.register_matrix_topology, making it available
by name in ESNLayer(topology="...").
| FUNCTION | DESCRIPTION |
|---|---|
orthogonal_matrix |
Haar-random orthogonal matrix via QR decomposition ( |
antisymmetric_matrix |
Random antisymmetric (skew-symmetric) matrix |
fast_spectral_initialization |
Recurrent matrix built at a target spectral radius analytically, with no
eigendecomposition ( |
delay_line, delay_line_backward, simple_cycle, cycle_jumps, self_loop_cycle |
Deterministic-minimal (Rodan & Tiňo) reservoirs — a pure delay line, a
delay line with a backward connection, a unidirectional cycle, a cycle with
regular jumps, and a self-loop cycle ( |
toeplitz, band, block_diagonal |
Structured reservoirs — a Toeplitz (constant-per-diagonal) matrix, a banded
matrix, and a block-diagonal matrix ( |
singular_spectrum, eigen_spectrum |
Dense random matrices with prescribed singular values or a real/complex conjugate-pair eigenvalue spectrum. Both preserve the supplied profile. |
signed_permutation, householder_orthogonal |
Orthogonal structures from signed cycles or products of reflections. |
See Also
resdag.init.graphs : Graph-based topology generators. resdag.init.topology : Registry and initializer classes.
antisymmetric_matrix
¶
antisymmetric_matrix(
n: int,
scaling: float = 1.0,
seed: int | None = None,
*,
dtype: dtype = float32,
device: device | str | None = None
) -> Tensor
Build a random antisymmetric (skew-symmetric) matrix \(A - A^\top\).
Draws a standard-Gaussian matrix \(A\) and returns \(\text{scaling} \cdot (A - A^\top)\), which satisfies \(M = -M^\top\) exactly (to floating-point). Its eigenvalues are purely imaginary, so \(x \mapsto M x\) is a rotation generator: the flow it induces conserves \(\|x\|\), and a small forward-Euler step is near-norm-preserving — the stable long-memory regime exploited by the Euler State Network.
Because the matrix is not pre-scaled, a layer-level spectral_radius
rescales it cleanly (scaling preserves antisymmetry); control the raw scale
through scaling when no spectral_radius is given.
| PARAMETER | DESCRIPTION |
|---|---|
n
|
Matrix size (number of reservoir units).
TYPE:
|
scaling
|
Multiplicative gain applied to the antisymmetric part. Only the raw scale — the antisymmetry is independent of it.
TYPE:
|
seed
|
Seed for the Gaussian draw.
TYPE:
|
dtype
|
Real floating-point output and random-draw dtype.
TYPE:
|
device
|
Allocation and random-draw device (CPU by default). |
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Dense |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Examples:
>>> import torch
>>> from resdag.init.matrices.antisymmetric import antisymmetric_matrix
>>> m = antisymmetric_matrix(64, seed=0)
>>> torch.allclose(m, -m.t(), atol=1e-6)
True
By name in a layer (antisymmetric recurrent connectivity):
>>> from resdag.layers import ESNLayer
>>> reservoir = ESNLayer(
... 128, feedback_size=3, topology="antisymmetric", spectral_radius=0.9
... )
Source code in src/resdag/init/matrices/antisymmetric.py
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 | |
band
¶
band(
n: int,
weight: float = 0.1,
bandwidth: int = 1,
*,
dtype: dtype = float32,
device: device | str | None = None
) -> Tensor
Fill abs(i-j) <= bandwidth with weight and the rest with zero.
Requires 0 <= bandwidth < n. Zero gives a scaled identity; one gives
a tridiagonal matrix. The in-band weights are deterministic and constant.
| PARAMETER | DESCRIPTION |
|---|---|
n
|
Number of reservoir units, a positive integer.
TYPE:
|
weight
|
Constant assigned to every in-band entry, including the main diagonal.
TYPE:
|
bandwidth
|
Half-bandwidth, satisfying
TYPE:
|
dtype
|
Real floating-point output dtype.
TYPE:
|
device
|
Allocation device (CPU by default). |
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Dense symmetric |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If size, bandwidth, or dtype is invalid. |
Examples:
>>> matrix = band(6, weight=0.2, bandwidth=2)
>>> from resdag.layers import ESNLayer
>>> reservoir = ESNLayer(
... 100, feedback_size=3,
... recurrent_initializer=("band", {"bandwidth": 3}),
... )
Source code in src/resdag/init/matrices/structured.py
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 | |
block_diagonal
¶
block_diagonal(
n: int,
weight: float = 1.0,
block_size: int = 1,
*,
dtype: dtype = float32,
device: device | str | None = None
) -> Tensor
Fill complete diagonal blocks of size block_size with weight.
Requires 1 <= block_size <= n. Incomplete trailing rows/columns are
left zero. Each full block has rank at most one and eigenvalues
weight * block_size plus zeros. This isolates independent groups of
reservoir units while retaining the original constant-block behavior.
| PARAMETER | DESCRIPTION |
|---|---|
n
|
Number of reservoir units, a positive integer.
TYPE:
|
weight
|
Constant filling every element of each complete block.
TYPE:
|
block_size
|
Square block side length, satisfying
TYPE:
|
dtype
|
Real floating-point output dtype.
TYPE:
|
device
|
Allocation device (CPU by default). |
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Dense |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If size, block_size, or dtype is invalid. |
Examples:
>>> matrix = block_diagonal(7, weight=0.5, block_size=3)
>>> from resdag.layers import ESNLayer
>>> reservoir = ESNLayer(
... 100, feedback_size=3,
... recurrent_initializer=("block_diagonal", {"block_size": 5}),
... )
Source code in src/resdag/init/matrices/structured.py
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 | |
cycle_jumps
¶
cycle_jumps(
n: int,
cycle_weight: float = 0.1,
jump_weight: float = 0.1,
jump_size: int = 3,
*,
dtype: dtype = float32,
device: device | str | None = None
) -> Tensor
Add bidirectional jumps between regularly spaced nodes of a cycle.
The jump chain visits 0, jump_size, 2*jump_size, .... It closes back
to zero only if jump_size divides n; otherwise the trailing partial
jump is omitted. Jump edges overwrite any coincident cycle edges.
Requires 1 <= jump_size < n.
| PARAMETER | DESCRIPTION |
|---|---|
n
|
Number of reservoir units, a positive integer greater than jump_size.
TYPE:
|
cycle_weight
|
Constant weight of the unidirectional cycle edges.
TYPE:
|
jump_weight
|
Constant weight of both directions of each jump edge.
TYPE:
|
jump_size
|
Distance between successive jump-chain nodes. Must satisfy
TYPE:
|
dtype
|
Real floating-point output dtype.
TYPE:
|
device
|
Allocation device (CPU by default). |
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Dense |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If size, jump offset, or dtype is invalid. |
Examples:
>>> matrix = cycle_jumps(7, cycle_weight=0.1, jump_weight=0.5, jump_size=3)
>>> from resdag.layers import ESNLayer
>>> reservoir = ESNLayer(
... 100, feedback_size=3,
... recurrent_initializer=("cycle_jumps", {"jump_size": 5}),
... )
References
A. Rodan and P. Tiňo, "Simple Deterministically Constructed Cycle Reservoirs with Regular Jumps", Neural Computation, 24(7):1822–1852, 2012.
Source code in src/resdag/init/matrices/minimal.py
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 | |
delay_line
¶
delay_line(
n: int,
weight: float = 0.1,
shift: int = 1,
*,
dtype: dtype = float32,
device: device | str | None = None
) -> Tensor
Place weight on a subdiagonal shift places below the diagonal.
Requires 1 <= shift < n. The matrix is nilpotent: its eigenvalues are
all zero. Control its scale through weight; an outer spectral-radius
rescale cannot assign it a nonzero radius.
| PARAMETER | DESCRIPTION |
|---|---|
n
|
Number of reservoir units; a positive integer greater than
TYPE:
|
weight
|
Constant weight of every forward connection. It controls how much past activity remains after each shift along the delay line.
TYPE:
|
shift
|
Subdiagonal offset. One connects each unit to its next neighbour;
larger offsets skip units. Must satisfy
TYPE:
|
dtype
|
Real floating-point output dtype; float64 avoids a float32 conversion.
TYPE:
|
device
|
Allocation device, CPU by default. CUDA/MPS allocation is direct. |
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Dense |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Examples:
>>> matrix = delay_line(6, weight=0.5, shift=2, dtype=torch.float64)
>>> from resdag.layers import ESNLayer
>>> reservoir = ESNLayer(
... 100, feedback_size=3, spectral_radius=None,
... recurrent_initializer=("delay_line", {"weight": 0.5}),
... )
References
A. Rodan and P. Tiňo, "Minimum Complexity Echo State Network", IEEE Transactions on Neural Networks, 22(1):131–144, 2011.
Source code in src/resdag/init/matrices/minimal.py
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 | |
delay_line_backward
¶
delay_line_backward(
n: int,
weight: float = 0.1,
backward_weight: float = 0.1,
shift: int = 1,
backward_shift: int = 1,
*,
dtype: dtype = float32,
device: device | str | None = None
) -> Tensor
Build a forward delay line plus a backward superdiagonal connection.
shift and backward_shift each satisfy 1 <= offset < n. The
weights and offsets of the two directions are independent.
| PARAMETER | DESCRIPTION |
|---|---|
n
|
Number of reservoir units, a positive integer.
TYPE:
|
weight
|
Weight on the forward subdiagonal.
TYPE:
|
backward_weight
|
Weight on the reverse superdiagonal. A negative weight changes the sign of backward feedback independently of the forward path.
TYPE:
|
shift
|
Forward subdiagonal offset, satisfying
TYPE:
|
backward_shift
|
Backward superdiagonal offset, satisfying
TYPE:
|
dtype
|
Real floating-point output dtype.
TYPE:
|
device
|
Allocation device (CPU by default). |
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Dense |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If size, offsets, or dtype are invalid. |
Examples:
>>> matrix = delay_line_backward(6, weight=0.1, backward_weight=-0.3)
>>> from resdag.layers import ESNLayer
>>> reservoir = ESNLayer(
... 100, feedback_size=3,
... recurrent_initializer=("delay_line_backward", {"backward_weight": -1.0}),
... )
References
A. Rodan and P. Tiňo, "Minimum Complexity Echo State Network", IEEE Transactions on Neural Networks, 22(1):131–144, 2011.
Source code in src/resdag/init/matrices/minimal.py
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 | |
fast_spectral_initialization
¶
fast_spectral_initialization(
n: int,
spectral_radius: float = 0.9,
seed: int | None = None,
*,
dtype: dtype = float32,
device: device | str | None = None
) -> Tensor
Build a recurrent matrix at a target spectral radius without eigvals.
Implements Gallicchio's Fast Spectral Initialization (FSI): entries are
drawn i.i.d. from \(\mathcal{U}(-a, a)\) with
\(a = \rho \sqrt{3 / n}\), so by the circular law the matrix's
spectral radius is \(\approx \rho\) by construction. No
eigendecomposition or power iteration is performed; the whole cost is the
random draw, which is what makes it attractive for large n.
The finite-size radius is approximate. The legacy registration retains
the layer's outer spectral estimation and rescaling. To skip that cost,
configure get_recurrent_initializer("fast_spectral_initialization", spectral_radius=0.9, rescale=False) and pass the resulting object to the
layer. That explicitly accepts the finite-size approximation; the layer's
spectral_radius is then ignored without a warning.
| PARAMETER | DESCRIPTION |
|---|---|
n
|
Matrix size (number of reservoir units).
TYPE:
|
spectral_radius
|
Target spectral radius \(\rho\). For finite
TYPE:
|
seed
|
Seed for the uniform draw.
TYPE:
|
dtype
|
Real floating-point output and random-draw dtype.
TYPE:
|
device
|
Allocation and random-draw device (CPU by default). |
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Dense |
Examples:
>>> from resdag.init import get_recurrent_initializer
>>> from resdag.layers import ESNLayer
>>> reservoir = ESNLayer(
... 2000, feedback_size=3,
... recurrent_initializer=get_recurrent_initializer(
... "fast_spectral_initialization", spectral_radius=0.95, rescale=False
... ),
... )
References
C. Gallicchio, "Fast Spectral Radius Initialization for Recurrent Neural Networks", in Recent Advances in Big Data and Deep Learning (INNSBDDL 2019), Springer, 2020, pp. 380–390.
Source code in src/resdag/init/matrices/fsi.py
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 | |
orthogonal_matrix
¶
orthogonal_matrix(
n: int,
gain: float = 1.0,
seed: int | None = None,
*,
dtype: dtype = float32,
device: device | str | None = None
) -> Tensor
Build a random orthogonal matrix via QR decomposition.
Draws a standard Gaussian matrix, takes its QR decomposition, and fixes the signs so the result is drawn from the Haar (uniform) distribution over orthogonal matrices.
This topology is pre-scaled: an orthogonal matrix already has all its
singular values equal to abs(gain) (norm-preserving for abs(gain)=1), which is
the structural property it exists to provide. Because the layer-level
spectral-radius rescale would collapse every singular value to the target
radius and destroy that property, it is suppressed for this topology. A
layer spectral_radius passed alongside this topology is therefore
ignored (with a warning); control the scale through gain instead.
An explicit get_recurrent_initializer("orthogonal", rescale=True)
configuration opts into the outer scale, changing the specified gain.
| PARAMETER | DESCRIPTION |
|---|---|
n
|
Matrix size (number of reservoir units).
TYPE:
|
gain
|
Scaling factor applied to the orthogonal matrix. With
TYPE:
|
seed
|
Seed for the Gaussian draw.
TYPE:
|
dtype
|
Real floating-point output dtype. CPU QR retains float64 precision; accelerator QR uses the requested dtype, promoting half to float32.
TYPE:
|
device
|
Output device (CPU by default). CUDA uses native QR. MPS's unsupported QR operation runs on CPU and the resulting factor returns to MPS. |
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Dense orthogonal matrix of shape |
Examples:
>>> from resdag.layers import ESNLayer
>>> reservoir = ESNLayer(500, feedback_size=3, topology="orthogonal")
>>> reservoir = ESNLayer(
... 500, feedback_size=3, topology=("orthogonal", {"seed": 42})
... )
Source code in src/resdag/init/matrices/orthogonal.py
16 17 18 19 20 21 22 23 24 25 26 27 28 29 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 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 | |
self_loop_cycle
¶
self_loop_cycle(
n: int,
cycle_weight: float = 0.1,
self_loop_weight: float = 0.1,
*,
dtype: dtype = float32,
device: device | str | None = None
) -> Tensor
Build a directed cycle with a constant self-connection on every unit.
The diagonal is assigned self_loop_weight. For n=1, this overwrites
the cycle's single self-connection.
| PARAMETER | DESCRIPTION |
|---|---|
n
|
Number of reservoir units, a positive integer.
TYPE:
|
cycle_weight
|
Constant weight of the cycle edges.
TYPE:
|
self_loop_weight
|
Weight on every diagonal self-connection. For
TYPE:
|
dtype
|
Real floating-point output dtype.
TYPE:
|
device
|
Allocation device (CPU by default). |
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Dense |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If size or dtype is invalid. |
Examples:
>>> matrix = self_loop_cycle(6, cycle_weight=0.9, self_loop_weight=0.1)
>>> from resdag.layers import ESNLayer
>>> reservoir = ESNLayer(
... 100, feedback_size=3,
... recurrent_initializer=("self_loop_cycle", {"self_loop_weight": 0.2}),
... )
References
A. Rodan and P. Tiňo, "Minimum Complexity Echo State Network", IEEE Transactions on Neural Networks, 22(1):131–144, 2011.
Source code in src/resdag/init/matrices/minimal.py
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 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 | |
simple_cycle
¶
simple_cycle(
n: int,
weight: float = 0.1,
*,
dtype: dtype = float32,
device: device | str | None = None
) -> Tensor
Build one directed ring with constant weight on every edge.
The subdiagonal and top-right corner form a cyclic permutation scaled by
weight. Every eigenvalue has magnitude abs(weight); a requested
outer radius rescales the cycle without changing its connections.
| PARAMETER | DESCRIPTION |
|---|---|
n
|
Number of reservoir units, a positive integer. One gives a self-loop.
TYPE:
|
weight
|
Constant weight on every cycle edge. The raw spectral radius is
TYPE:
|
dtype
|
Real floating-point output dtype.
TYPE:
|
device
|
Allocation device (CPU by default). |
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Dense |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If size or dtype is invalid. |
Examples:
>>> matrix = simple_cycle(6, weight=0.9)
>>> from resdag.layers import ESNLayer
>>> reservoir = ESNLayer(
... 100, feedback_size=3, recurrent_initializer="simple_cycle",
... spectral_radius=0.9,
... )
References
A. Rodan and P. Tiňo, "Minimum Complexity Echo State Network", IEEE Transactions on Neural Networks, 22(1):131–144, 2011.
Source code in src/resdag/init/matrices/minimal.py
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 | |
singular_spectrum
¶
singular_spectrum(
n: int,
singular_values: Sequence[float] | Tensor | None = None,
seed: int | None = None,
*,
dtype: dtype = float32,
device: device | str | None = None
) -> Tensor
Build U @ diag(singular_values) @ V.T from independent Haar factors.
Supply exactly n finite nonnegative singular values, in any order.
If omitted, they decrease linearly from 1 to 0.1 (n=1 uses 1).
Zero singular values allow rank-deficient reservoirs. This controls the
one-step linear gains, not the eigenvalues or spectral radius. Nonlinear
or leaky reservoir updates need their own stability analysis.
seed uses a local RNG on device; None uses torch's global RNG.
dtype/device control allocation and arithmetic; half-precision
decompositions are computed in float32 then cast to the requested dtype.
MPS QR uses a CPU fallback; CUDA QR stays on CUDA.
An outer radius rescale would change all supplied singular values, so this
builder is registered as prescaled. Explicit rescale=True opts in.
| PARAMETER | DESCRIPTION |
|---|---|
n
|
Matrix size, a positive integer.
TYPE:
|
singular_values
|
One-dimensional sequence of exactly n finite nonnegative values. Order is arbitrary. None uses a linear profile from 1 down to 0.1. Python sequences are converted directly into the computation dtype.
TYPE:
|
seed
|
Local RNG seed. Repeated calls with the same seed, device, dtype, and parameters produce the same matrix without changing global RNG.
TYPE:
|
dtype
|
Real floating-point output dtype. Float64 computations retain the supplied double precision; half/bfloat16 QR is promoted to float32.
TYPE:
|
device
|
Output device (CPU by default). MPS QR uses a CPU fallback. |
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Dense |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If size, dtype, spectrum shape, signs, or finiteness are invalid. |
TypeError
|
If seed is neither an integer nor None. |
Examples:
>>> matrix = singular_spectrum(3, [1.0, 0.5, 0.0], seed=4, dtype=torch.float64)
>>> from resdag.init import get_recurrent_initializer
>>> from resdag.layers import ESNLayer
>>> reservoir = ESNLayer(
... 3, feedback_size=1,
... recurrent_initializer=get_recurrent_initializer(
... "singular_spectrum", singular_values=[1.0, 0.5, 0.0],
... seed=4, rescale=False,
... ),
... )
Source code in src/resdag/init/matrices/spectral.py
18 19 20 21 22 23 24 25 26 27 28 29 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 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 | |
eigen_spectrum
¶
eigen_spectrum(
n: int,
eigenvalues: Sequence[complex] | Tensor | None = None,
seed: int | None = None,
*,
dtype: dtype = float32,
device: device | str | None = None
) -> Tensor
Build a real normal matrix with prescribed real/complex-pair eigenvalues.
Supply exactly n finite eigenvalues, with nonreal values in conjugate
pairs (order is arbitrary). A pair a ± bi becomes a real block
[[a, -b], [b, a]]. A Haar orthogonal similarity transforms the block
diagonal matrix without changing its eigenvalues. If omitted, eigenvalues
are real and spaced from -0.9 to 0.9 (n=1 uses -0.9).
The result is normal: its singular values are the eigenvalue magnitudes.
This construction does not control nonnormal transient amplification.
dtype is real floating-point; float64 retains double precision.
seed is local and device-correct; half-precision QR uses float32.
MPS QR runs on CPU; the returned matrix remains on the requested device.
The complete spectrum is preserved unless outer rescaling is explicitly
enabled with get_recurrent_initializer(..., rescale=True).
| PARAMETER | DESCRIPTION |
|---|---|
n
|
Matrix size, a positive integer.
TYPE:
|
eigenvalues
|
Exactly n finite real or complex values. Nonreal values must come in conjugate pairs, in any order; conjugates are matched within a relative tolerance of 1e-12 and absolute tolerance of 1e-14. A matched pair uses the first supplied value and its conjugate. None uses real values linearly spaced from -0.9 to 0.9.
TYPE:
|
seed
|
Seed of the local RNG used for the orthogonal similarity factor. None draws from the global torch RNG.
TYPE:
|
dtype
|
Real floating-point output dtype. Float64 retains double precision; half/bfloat16 QR is computed in float32 then cast.
TYPE:
|
device
|
Output device (CPU by default). MPS QR uses a CPU fallback. |
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Dense real normal |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If size, dtype, number of eigenvalues, finiteness, or conjugate pairing is invalid. A real matrix cannot have an unpaired nonreal root. |
TypeError
|
If seed is neither an integer nor None. |
Examples:
>>> matrix = eigen_spectrum(3, [0.5, 0.2 + 0.7j, 0.2 - 0.7j], seed=4)
>>> from resdag.init import get_recurrent_initializer
>>> from resdag.layers import ESNLayer
>>> reservoir = ESNLayer(
... 3, feedback_size=1,
... recurrent_initializer=get_recurrent_initializer(
... "eigen_spectrum", eigenvalues=[0.5, 0.2 + 0.7j, 0.2 - 0.7j],
... seed=4, rescale=False,
... ),
... )
Source code in src/resdag/init/matrices/spectral.py
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 | |
signed_permutation
¶
signed_permutation(
n: int,
gain: float = 1.0,
seed: int | None = None,
*,
dtype: dtype = float32,
device: device | str | None = None
) -> Tensor
Build a random permutation with independent random signs, times gain.
Each row and column has exactly one nonzero when gain != 0. All
singular values and eigenvalue magnitudes equal abs(gain). These
matrices preserve norm for abs(gain)=1 while allowing signed cycles
instead of mixing every state coordinate as a dense Haar draw does.
A direct call is O(n²) because the returned tensor is dense. Using this
registered initializer in an ESN with sparse=True constructs the
compressed weights directly in O(n) storage and uses a CPU gather update.
The permutation and signs use a local device RNG when seed is given.
| PARAMETER | DESCRIPTION |
|---|---|
n
|
Matrix size, a positive integer.
TYPE:
|
gain
|
Finite multiplier on the signed permutation. All singular values equal abs(gain). Zero gives an all-zero matrix; negative gains are valid.
TYPE:
|
seed
|
Local seed for the random permutation and signs. None uses torch's global RNG; an explicit seed leaves the global RNG unchanged.
TYPE:
|
dtype
|
Real floating-point output dtype.
TYPE:
|
device
|
Allocation and random-draw device (CPU by default). |
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Dense |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If size or dtype is invalid, or gain is nonfinite. |
TypeError
|
If seed is neither an integer nor None. |
Examples:
>>> matrix = signed_permutation(100, gain=0.9, seed=4)
>>> from resdag.layers import ESNLayer
>>> reservoir = ESNLayer(
... 100, feedback_size=3, spectral_radius=None,
... recurrent_initializer=("signed_permutation", {"gain": 0.9, "seed": 4}),
... )
Source code in src/resdag/init/matrices/orthogonal_structures.py
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 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 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 | |
householder_orthogonal
¶
householder_orthogonal(
n: int,
gain: float = 1.0,
reflectors: int | None = None,
seed: int | None = None,
*,
dtype: dtype = float32,
device: device | str | None = None
) -> Tensor
Build gain * H_k ... H_1, with H_i = I - 2 v_i v_i.T.
Each v_i is an independently sampled Gaussian direction, normalized
to unit norm. reflectors=None uses n reflections; zero gives a
scaled identity. All singular values equal abs(gain). For k < n
at least n-k directions are unchanged before applying gain; choose
the number of reflections to balance mixing against initialization cost.
Dense rank-one updates cost O(k n²), with O(n²) storage. Thus the default
k=n costs O(n³); a fixed small k costs O(n²). The returned matrix
still uses dense recurrent multiplication. This fixed-reflection product
is not a Haar-uniform draw. Half-precision arithmetic is promoted to
float32 until the result is cast to the requested dtype.
| PARAMETER | DESCRIPTION |
|---|---|
n
|
Matrix size, a positive integer.
TYPE:
|
gain
|
Finite multiplier. All singular values equal abs(gain); zero and negative gains are allowed.
TYPE:
|
reflectors
|
Nonnegative number of reflections. None uses n; zero gives gain * I. A fixed small value reduces setup work but leaves more directions unchanged. The output is still a dense matrix.
TYPE:
|
seed
|
Local seed for Gaussian reflection directions on the requested device. None uses torch's global RNG.
TYPE:
|
dtype
|
Real floating-point output dtype. Half/bfloat16 arithmetic is promoted to float32 before the final cast.
TYPE:
|
device
|
Allocation, random-draw, and computation device (CPU by default). |
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Dense scaled orthogonal |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If size, dtype, reflector count, or gain is invalid. |
TypeError
|
If seed is neither an integer nor None. |
Examples:
>>> matrix = householder_orthogonal(100, gain=0.9, reflectors=8, seed=4)
>>> from resdag.layers import ESNLayer
>>> reservoir = ESNLayer(
... 100, feedback_size=3, spectral_radius=None,
... recurrent_initializer=("householder_orthogonal", {"reflectors": 8, "gain": 0.9}),
... )
Source code in src/resdag/init/matrices/orthogonal_structures.py
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 | |
toeplitz
¶
toeplitz(
n: int,
weight: float = 0.1,
decay: float = 1.0,
bandwidth: int | None = None,
*,
dtype: dtype = float32,
device: device | str | None = None
) -> Tensor
Set M[i,j] = weight * decay**abs(i-j) inside an optional band.
Every diagonal is constant, and the matrix is symmetric. bandwidth=None
fills all diagonals; otherwise only offsets up to a nonnegative bandwidth
are populated. This is a deterministic geometric Toeplitz construction.
| PARAMETER | DESCRIPTION |
|---|---|
n
|
Number of reservoir units, a positive integer.
TYPE:
|
weight
|
Main-diagonal weight and the scale of every other diagonal.
TYPE:
|
decay
|
Geometric factor per diagonal offset.
TYPE:
|
bandwidth
|
Maximum populated absolute offset. Must be nonnegative when supplied; None keeps every diagonal. Zero gives a scaled identity.
TYPE:
|
dtype
|
Real floating-point output and power-computation dtype.
TYPE:
|
device
|
Allocation and computation device (CPU by default). |
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Dense |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If size, bandwidth, or dtype is invalid. |
Examples:
>>> matrix = toeplitz(6, decay=0.5, bandwidth=2, dtype=torch.float64)
>>> from resdag.layers import ESNLayer
>>> reservoir = ESNLayer(
... 100, feedback_size=3,
... recurrent_initializer=("toeplitz", {"decay": 0.5, "bandwidth": 5}),
... )
Source code in src/resdag/init/matrices/structured.py
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 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 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 | |
Specification types and resolution¶
Resolvers preserve each initializer's supported seed and device conventions.
select_recurrent_spec accepts either the original topology spelling or
recurrent_initializer and rejects supplying both.
utils
¶
Initialization utility functions.
TopologySpec
module-attribute
¶
TopologySpec = (
None | str | Callable | tuple[str | Callable, dict[str, Any]] | TopologyInitializer
)
InitializerSpec
module-attribute
¶
InitializerSpec = (
None
| str
| Callable
| tuple[str | Callable, dict[str, Any]]
| InputFeedbackInitializer
)
resolve_topology
¶
resolve_topology(
spec: TopologySpec, seed: SeedLike = None
) -> TopologyInitializer | None
Resolve a topology specification to a TopologyInitializer object.
Accepts six formats:
None— returns None (use default random initialization)str— registry name, uses registered default parameterstuple[str, dict]— registry name with parameter overridescallable— any matrix builderfn(n, **kw) -> matrix | graphor in-placefn(tensor, **kw); wrapped inMatrixTopologytuple[callable, dict]— matrix builder with bound parametersTopologyInitializer— already resolved, returned as-is
| PARAMETER | DESCRIPTION |
|---|---|
spec
|
Topology specification in one of the accepted formats.
TYPE:
|
seed
|
Seed forwarded to the underlying builder for reproducibility. It is
applied only to the |
| RETURNS | DESCRIPTION |
|---|---|
TopologyInitializer or None
|
Resolved topology object, or None if spec was None. |
| RAISES | DESCRIPTION |
|---|---|
TypeError
|
If spec is not one of the accepted types. |
Examples:
>>> resolve_topology("erdos_renyi")
GraphTopology(...)
>>> resolve_topology("erdos_renyi", seed=42)
GraphTopology(...)
>>> resolve_topology(("watts_strogatz", {"k": 6, "p": 0.1}))
GraphTopology(...)
>>> resolve_topology(my_matrix_fn)
MatrixTopology(...)
>>> resolve_topology((my_matrix_fn, {"blocks": 4}))
MatrixTopology(...)
>>> resolve_topology(get_topology("ring_chord"))
GraphTopology(...)
Source code in src/resdag/init/utils/resolve.py
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 | |
resolve_initializer
¶
resolve_initializer(
spec: InitializerSpec, seed: SeedLike = None
) -> InputFeedbackInitializer | None
Resolve an initializer specification to an InputFeedbackInitializer object.
Accepts six formats:
None— returns None (use default random initialization)str— registry name, uses registered default parameterstuple[str, dict]— registry name with parameter overridescallable— any matrix builderfn(rows, cols, **kw) -> matrixor in-placefn(tensor, **kw); wrapped inFunctionInitializertuple[callable, dict]— matrix builder with bound parametersInputFeedbackInitializer— already resolved, returned as-is
| PARAMETER | DESCRIPTION |
|---|---|
spec
|
Initializer specification in one of the accepted formats.
TYPE:
|
seed
|
Seed forwarded to the underlying initializer for reproducibility. It
is applied only to the |
| RETURNS | DESCRIPTION |
|---|---|
InputFeedbackInitializer or None
|
Resolved initializer object, or None if spec was None. |
| RAISES | DESCRIPTION |
|---|---|
TypeError
|
If spec is not one of the accepted types. |
Examples:
>>> resolve_initializer("pseudo_diagonal")
PseudoDiagonalInitializer(...)
>>> resolve_initializer("random", seed=42)
RandomInputInitializer(...)
>>> resolve_initializer(("chebyshev", {"p": 0.5, "q": 3.0}))
ChebyshevInitializer(...)
>>> resolve_initializer(torch.nn.init.xavier_uniform_)
FunctionInitializer(...)
>>> resolve_initializer((my_matrix_fn, {"scale": 0.5}))
FunctionInitializer(...)
>>> resolve_initializer(get_input_feedback("random"))
RandomInitializer(...)
Source code in src/resdag/init/utils/resolve.py
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 337 338 339 340 341 342 343 344 | |
resolve_recurrent_initializer
¶
resolve_recurrent_initializer(
spec: RecurrentInitializerSpec, seed: SeedLike = None
) -> TopologyInitializer | None
Resolve a graph or matrix recurrent initializer using the shared registry.
Strings, (name_or_callable, kwargs) tuples, dimension-based or in-place
callables, and preconfigured objects retain resolve_topology's
seeding and calling conventions.
Source code in src/resdag/init/utils/resolve.py
55 56 57 58 59 60 61 62 63 64 65 | |
select_recurrent_spec
¶
select_recurrent_spec(
*,
topology: TopologySpec = None,
recurrent_initializer: RecurrentInitializerSpec = None
) -> RecurrentInitializerSpec
Choose the recurrent specification, rejecting two explicit choices.
topology is the original spelling. Both parameters accept graph and
matrix builders; recurrent_initializer makes that scope explicit.
Source code in src/resdag/init/utils/resolve.py
40 41 42 43 44 45 46 47 48 49 50 51 52 | |