Skip to content

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
def 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.
    """
    if rescale is not None and not isinstance(rescale, bool):
        raise TypeError("rescale must be True, False, or None")
    initializer = get_topology(name, **builder_kwargs)
    initializer.rescale = rescale
    return initializer

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
def 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`.
    """
    return register_matrix_topology(name, prescaled=prescaled, **default_kwargs)

show_recurrent_initializers

show_recurrent_initializers(name: str | None = None) -> list[str] | None

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
def show_recurrent_initializers(name: str | None = None) -> list[str] | None:
    """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.
    """
    if name is not None:
        return show_topologies(name)
    names = sorted(_TOPOLOGY_REGISTRY)
    print("\nAvailable recurrent initializers (graph and matrix):\n")
    for registered_name in names:
        _, _, wrapper, _ = _TOPOLOGY_REGISTRY[registered_name]
        kind = "graph" if wrapper is GraphTopology else "matrix"
        print(f"  - {registered_name} ({kind})")
    print(f"\nTotal: {len(names)}\n")
    return names

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 True, initialize skips the outer scale_to_spectral_radius rescale so that structure is preserved, and warns if a layer-level spectral_radius is also passed (the two collide). Defaults to False.

TYPE: bool

rescale

Explicit outer scaling policy. None keeps the registration's prescaled policy; False skips spectral estimation/scaling without a warning; True applies a requested layer radius even when prescaled.

TYPE: bool or None

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
def build_sparse(
    self,
    n: int,
    *,
    dtype: torch.dtype,
    device: torch.device,
    spectral_radius: float | None = None,
) -> torch.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.
    """
    dense = torch.empty(n, n, dtype=dtype, device=device)
    self.initialize(dense, spectral_radius=spectral_radius)
    return dense.to_sparse_csr()

initialize abstractmethod

initialize(weight: Tensor, spectral_radius: float | None = None) -> Tensor

Initialize a weight tensor using graph topology.

PARAMETER DESCRIPTION
weight

The weight tensor to initialize, shape (n, n) for recurrent weights. This tensor is modified in-place.

TYPE: Tensor

spectral_radius

Target spectral radius for scaling. If None, no scaling is applied.

TYPE: float DEFAULT: None

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
@abstractmethod
def initialize(
    self,
    weight: torch.Tensor,
    spectral_radius: float | None = None,
) -> torch.Tensor:
    """
    Initialize a weight tensor using graph topology.

    Parameters
    ----------
    weight : torch.Tensor
        The weight tensor to initialize, shape `(n, n)` for recurrent
        weights. This tensor is modified in-place.
    spectral_radius : float, optional
        Target spectral radius for scaling. If None, no scaling is applied.

    Returns
    -------
    torch.Tensor
        The initialized weight tensor (same as input, modified in-place).
    """
    pass

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 (n: int, **kwargs) -> nx.Graph | nx.DiGraph. Must return a NetworkX graph with weighted edges.

TYPE: callable

graph_kwargs

Keyword arguments to pass to the graph function.

TYPE: dict DEFAULT: None

prescaled

If True, the graph builder already bakes its own spectral structure into the adjacency matrix (e.g. spectral_cascade's graded per-clique radii). The outer scale_to_spectral_radius rescale is then skipped in initialize, and a warning is emitted if a spectral_radius is nonetheless requested, since the two meanings of spectral_radius collide.

TYPE: bool DEFAULT: False

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: bool or None DEFAULT: None

ATTRIBUTE DESCRIPTION
graph_func

The graph generation function.

TYPE: callable

graph_kwargs

Keyword arguments for the graph function.

TYPE: dict

prescaled

Whether the outer spectral-radius rescale is suppressed (see above).

TYPE: bool

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
def __init__(
    self,
    graph_func: Callable,
    graph_kwargs: dict[str, Any] | None = None,
    prescaled: bool = False,
    rescale: bool | None = None,
):
    self.graph_func = graph_func
    self.graph_kwargs = graph_kwargs or {}
    self.prescaled = prescaled
    if rescale is not None and not isinstance(rescale, bool):
        raise TypeError("rescale must be True, False, or None")
    self.rescale = rescale

initialize

initialize(weight: Tensor, spectral_radius: float | None = None) -> Tensor

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 (n, n).

TYPE: Tensor

spectral_radius

Target spectral radius for the weight matrix. Ignored (with a warning) when the topology is prescaled.

TYPE: float DEFAULT: None

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
def initialize(
    self,
    weight: torch.Tensor,
    spectral_radius: float | None = None,
) -> torch.Tensor:
    """
    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.

    Parameters
    ----------
    weight : torch.Tensor
        Square tensor to initialize, shape `(n, n)`.
    spectral_radius : float, optional
        Target spectral radius for the weight matrix. Ignored (with a
        warning) when the topology is `prescaled`.

    Returns
    -------
    torch.Tensor
        Initialized weight tensor (modified in-place).

    Raises
    ------
    ValueError
        If weight is not 2D or not square.
    """
    if weight.ndim != 2:
        raise ValueError(f"Weight must be 2D, got shape {weight.shape}")

    if weight.shape[0] != weight.shape[1]:
        raise ValueError(f"Weight must be square, got shape {weight.shape}")

    n = weight.shape[0]
    device = weight.device
    dtype = weight.dtype

    # Dense fast path: generators decorated with ``register_dense_adjacency``
    # advertise a vectorized NumPy builder, so the dense adjacency is built
    # directly and the (pure-overhead) NetworkX round-trip is skipped.
    adj_matrix = self._build_adjacency(n)

    # Convert to torch tensor
    weight_data = torch.from_numpy(adj_matrix).to(device=device, dtype=dtype)

    # Apply spectral radius scaling if requested.  Pre-scaled topologies bake
    # their own spectral structure into the adjacency matrix, so the outer
    # rescale is suppressed (and the collision is surfaced as a warning).
    if spectral_radius is not None and self.rescale is not False:
        if self.prescaled and self.rescale is None:
            _warn_prescaled_override(
                getattr(self.graph_func, "__name__", repr(self.graph_func)),
                spectral_radius,
            )
        else:
            weight_data = self._scale_spectral_radius(weight_data, spectral_radius)

    # Copy into weight tensor
    with torch.no_grad():
        weight.copy_(weight_data)

    return weight

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
def build_sparse(
    self,
    n: int,
    *,
    dtype: torch.dtype,
    device: torch.device,
    spectral_radius: float | None = None,
) -> torch.Tensor:
    """Build from graph edges without a dense Torch adjacency allocation."""
    from resdag.init.graphs._sparse import sparse_adjacency

    adjacency = sparse_adjacency(self.graph_func, n, self.graph_kwargs)
    result = torch.sparse_csr_tensor(
        torch.as_tensor(adjacency.indptr, dtype=torch.int64, device=device),
        torch.as_tensor(adjacency.indices, dtype=torch.int64, device=device),
        torch.as_tensor(adjacency.data, dtype=dtype, device=device),
        size=(n, n),
    )
    if spectral_radius is not None and self.rescale is not False:
        if self.prescaled and self.rescale is None:
            _warn_prescaled_override(
                getattr(self.graph_func, "__name__", repr(self.graph_func)), spectral_radius
            )
        else:
            result = scale_to_spectral_radius(result, spectral_radius)
    return result

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:

  1. Build style — fn(n, **kwargs) returning an (n, n) array-like: a torch.Tensor, a numpy.ndarray, or even a networkx graph (converted to its adjacency matrix).
  2. In-place style — fn(tensor, **kwargs) mutating a tensor in place, e.g. any torch.nn.init.*_ function.
PARAMETER DESCRIPTION
matrix_func

The matrix-building function (build style or in-place style).

TYPE: callable

matrix_kwargs

Keyword arguments bound to the function.

TYPE: dict DEFAULT: None

prescaled

If True, the builder already fixes the matrix's spectral structure (e.g. orthogonal's unit singular values or an explicitly prescribed eigenvalue spectrum). The outer scale_to_spectral_radius rescale is then skipped in initialize, and a warning is emitted if a spectral_radius is nonetheless requested.

TYPE: bool DEFAULT: False

seed

Reproducibility seed for in-place builders that take a generator= keyword (e.g. torch.nn.init.orthogonal_). At initialize time a torch.Generator seeded from seed on the weight's device is passed to the builder, so two topologies built with the same seed produce bit-identical recurrent matrices. Builders that take a seed argument directly receive it through matrix_kwargs instead and ignore this. Defaults to None (draws from torch's global RNG).

TYPE: int DEFAULT: None

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: bool or None DEFAULT: None

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
def __init__(
    self,
    matrix_func: Callable,
    matrix_kwargs: dict[str, Any] | None = None,
    prescaled: bool = False,
    seed: int | None = None,
    rescale: bool | None = None,
):
    self.matrix_func = matrix_func
    self.matrix_kwargs = dict(matrix_kwargs or {})
    self.prescaled = prescaled
    self.seed = _pop_generator_seed(matrix_func, self.matrix_kwargs, seed)
    if rescale is not None and not isinstance(rescale, bool):
        raise TypeError("rescale must be True, False, or None")
    self.rescale = rescale

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
def build_sparse(
    self,
    n: int,
    *,
    dtype: torch.dtype,
    device: torch.device,
    spectral_radius: float | None = None,
) -> torch.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.
    """
    from ._structured import known_matrix_csr

    matrix = known_matrix_csr(
        self.matrix_func, n, self.matrix_kwargs, dtype=dtype, device=device
    )
    if matrix is None:
        reference = torch.empty(0, device=device, dtype=dtype)
        result = _call_matrix_builder(
            self.matrix_func,
            reference,
            (n,),
            self.matrix_kwargs,
            seed=self.seed,
            scratch_shape=(n, n),
        )
        matrix = _coerce_to_matrix(result, (n, n), device, dtype, compact=True)
    if spectral_radius is not None and self.rescale is not False:
        if self.prescaled and self.rescale is None:
            _warn_prescaled_override(
                getattr(self.matrix_func, "__name__", repr(self.matrix_func)), spectral_radius
            )
        else:
            matrix = scale_to_spectral_radius(matrix, spectral_radius)
    return matrix

initialize

initialize(weight: Tensor, spectral_radius: float | None = None) -> Tensor

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 (n, n). Modified in-place.

TYPE: Tensor

spectral_radius

Target spectral radius. If None, no scaling is applied. Ignored (with a warning) when the topology is prescaled.

TYPE: float DEFAULT: None

RETURNS DESCRIPTION
Tensor

Initialized weight tensor (modified in-place).

RAISES DESCRIPTION
ValueError

If weight is not 2-D square, if the callable matches neither calling convention, or if the built matrix has the wrong shape.

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
def initialize(
    self,
    weight: torch.Tensor,
    spectral_radius: float | None = None,
) -> torch.Tensor:
    """
    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.

    Parameters
    ----------
    weight : torch.Tensor
        Square tensor to initialize, shape `(n, n)`. Modified in-place.
    spectral_radius : float, optional
        Target spectral radius. If None, no scaling is applied. Ignored
        (with a warning) when the topology is `prescaled`.

    Returns
    -------
    torch.Tensor
        Initialized weight tensor (modified in-place).

    Raises
    ------
    ValueError
        If `weight` is not 2-D square, if the callable matches neither
        calling convention, or if the built matrix has the wrong shape.
    """
    if weight.ndim != 2:
        raise ValueError(f"Weight must be 2D, got shape {weight.shape}")
    if weight.shape[0] != weight.shape[1]:
        raise ValueError(f"Weight must be square, got shape {weight.shape}")

    n = weight.shape[0]

    result = _call_matrix_builder(
        self.matrix_func, weight, (n,), self.matrix_kwargs, seed=self.seed
    )
    matrix = _coerce_to_matrix(result, (n, n), weight.device, weight.dtype)

    # Pre-scaled builders fix their own spectral structure (unit singular
    # values, analytic radius, ...), so the outer rescale is suppressed and
    # the collision is surfaced as a warning rather than silently applied.
    if spectral_radius is not None and self.rescale is not False:
        if self.prescaled and self.rescale is None:
            _warn_prescaled_override(
                getattr(self.matrix_func, "__name__", repr(self.matrix_func)),
                spectral_radius,
            )
        else:
            matrix = scale_to_spectral_radius(matrix, spectral_radius)

    with torch.no_grad():
        weight.copy_(matrix)

    return weight

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., "erdos_renyi", "watts_strogatz").

TYPE: str

**override_kwargs

Keyword arguments to override default graph parameters.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION
TopologyInitializer

Configured topology initializer (GraphTopology or MatrixTopology, depending on how the name was registered).

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
def get_topology(
    name: str,
    **override_kwargs: Any,
) -> TopologyInitializer:
    """
    Get a pre-configured topology initializer by name.

    Parameters
    ----------
    name : str
        Name of the topology (e.g., `"erdos_renyi"`, `"watts_strogatz"`).
    **override_kwargs
        Keyword arguments to override default graph parameters.

    Returns
    -------
    TopologyInitializer
        Configured topology initializer (`GraphTopology` or
        `MatrixTopology`, depending on how the name was registered).

    Raises
    ------
    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.
    """
    if name not in _TOPOLOGY_REGISTRY:
        available = ", ".join(_TOPOLOGY_REGISTRY.keys())
        raise ValueError(f"Unknown topology '{name}'. Available topologies: {available}")

    builder_func, default_kwargs, wrapper_class, prescaled = _TOPOLOGY_REGISTRY[name]

    # Merge default kwargs with overrides
    kwargs = {**default_kwargs, **override_kwargs}

    return wrapper_class(builder_func, kwargs, prescaled=prescaled)

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

prescaled

Mark the topology as already carrying its own spectral structure (e.g. spectral_cascade's graded per-clique radii). When True the wrapper resdag.init.topology.GraphTopology skips the outer resdag.init.topology.scale_to_spectral_radius rescale and warns if a layer-level spectral_radius is also requested.

TYPE: bool DEFAULT: False

**default_kwargs

Default keyword arguments for the graph function.

TYPE: Any DEFAULT: {}

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.Graph or nx.DiGraph with 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
def 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`.

    Parameters
    ----------
    name : str
        Unique name for the topology.
    prescaled : bool, default=False
        Mark the topology as already carrying its own spectral structure (e.g.
        `spectral_cascade`'s graded per-clique radii). When `True` the
        wrapper `resdag.init.topology.GraphTopology` skips the outer
        `resdag.init.topology.scale_to_spectral_radius` rescale and warns
        if a layer-level `spectral_radius` is also requested.
    **default_kwargs
        Default keyword arguments for the graph function.

    Returns
    -------
    callable
        Decorator function that registers and returns the graph function.

    Raises
    ------
    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.Graph` or `nx.DiGraph` with weighted edges.
    - Registered topologies can be accessed via `get_topology`.
    """

    def decorator(graph_func: Callable) -> Callable:
        if name in _TOPOLOGY_REGISTRY:
            raise ValueError(f"Topology '{name}' is already registered")
        _TOPOLOGY_REGISTRY[name] = (graph_func, default_kwargs, GraphTopology, prescaled)
        return graph_func

    return decorator

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

prescaled

Mark the topology as already fixing its own spectral structure (e.g. orthogonal's unit singular values, or a prescribed full eigenvalue spectrum). When True the wrapper resdag.init.topology.MatrixTopology skips the outer resdag.init.topology.scale_to_spectral_radius rescale and warns if a layer-level spectral_radius is also requested.

TYPE: bool DEFAULT: False

**default_kwargs

Default keyword arguments for the matrix function.

TYPE: Any DEFAULT: {}

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.Tensor or numpy.ndarray.
  • Registered topologies are accessed via get_topology or by name in ESNLayer(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
def 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.

    Parameters
    ----------
    name : str
        Unique name for the topology.
    prescaled : bool, default=False
        Mark the topology as already fixing its own spectral structure (e.g.
        `orthogonal`'s unit singular values, or a prescribed full eigenvalue
        spectrum). When
        `True` the wrapper `resdag.init.topology.MatrixTopology` skips
        the outer `resdag.init.topology.scale_to_spectral_radius` rescale
        and warns if a layer-level `spectral_radius` is also requested.
    **default_kwargs
        Default keyword arguments for the matrix function.

    Returns
    -------
    callable
        Decorator function that registers and returns the matrix function.

    Raises
    ------
    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.Tensor` or `numpy.ndarray`.
    - Registered topologies are accessed via `get_topology` or by name
      in `ESNLayer(topology="...")`, identically to graph topologies.
    """

    def decorator(matrix_func: Callable) -> Callable:
        if name in _TOPOLOGY_REGISTRY:
            raise ValueError(f"Topology '{name}' is already registered")
        _TOPOLOGY_REGISTRY[name] = (matrix_func, default_kwargs, MatrixTopology, prescaled)
        return matrix_func

    return decorator

estimate_spectral_radius

estimate_spectral_radius(matrix: Tensor) -> float

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

RETURNS DESCRIPTION
float

The estimated largest absolute eigenvalue max|lambda|.

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
def estimate_spectral_radius(matrix: torch.Tensor) -> float:
    """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.

    Parameters
    ----------
    matrix : torch.Tensor
        Square matrix whose spectral radius is wanted.

    Returns
    -------
    float
        The estimated largest absolute eigenvalue `max|lambda|`.

    See Also
    --------
    scale_to_spectral_radius : Uses this to rescale a matrix to a target radius.
    """
    if matrix.ndim != 2 or matrix.shape[0] != matrix.shape[1] or matrix.shape[0] == 0:
        raise ValueError("matrix must be a non-empty square matrix.")
    values = matrix.values() if matrix.layout == torch.sparse_csr else matrix
    if matrix.layout == torch.sparse_csr and matrix.is_complex():
        # Some Torch complex operations inspect the view's sparse parent for
        # strides. An independent O(nnz) value tensor keeps validation strided.
        values = values.clone()
    if not bool(torch.isfinite(values).all()):
        raise ValueError("matrix must contain only finite values.")
    # MPS has no complex eigvals or complex power-iteration support. Radius
    # measurement is an initialization/diagnostic operation, so use the CPU
    # implementation while keeping recurrent weights and CUDA work in place.
    if matrix.device.type == "mps":
        return estimate_spectral_radius(matrix.detach().cpu())
    n = matrix.shape[0]

    if matrix.layout == torch.sparse_csr:
        if n <= 2:
            return _dense_eigvals_radius(matrix.to_dense())
        # Stored CSR slots can remain after in-place zeroing or a zero target.
        if matrix._nnz() == 0 or not bool((values != 0).any()):
            return 0.0
        rows = torch.repeat_interleave(
            torch.arange(n, device=matrix.device), matrix.crow_indices().diff()
        )
        columns = matrix.col_indices()
        if bool((columns >= rows).all()) or bool((columns <= rows).all()):
            diagonal = values[columns == rows]
            return float(diagonal.abs().max().item()) if diagonal.numel() else 0.0
        radius = _functional_csr_radius(matrix)
        if radius is not None:
            return radius
        radius = _sparse_eigs_radius(matrix)
        if radius is None:
            raise RuntimeError(
                "Sparse spectral-radius estimation did not converge; no dense fallback was "
                "allocated. Use a prescaled initializer or omit automatic spectral scaling."
            )
        return radius

    if n <= _DENSE_EIGVALS_MAX_N:
        return _dense_eigvals_radius(matrix)

    if _is_sparse(matrix):
        radius = _sparse_eigs_radius(matrix)
        if radius is not None:
            return radius

    # A stationary power estimate can belong to a subdominant eigenspace.
    # Dense scaling therefore uses the eigensolver, never that heuristic.
    return _dense_eigvals_radius(matrix)

scale_to_spectral_radius

scale_to_spectral_radius(matrix: Tensor, target_radius: float) -> Tensor

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

target_radius

Desired largest absolute eigenvalue.

TYPE: float

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
def scale_to_spectral_radius(matrix: torch.Tensor, target_radius: float) -> torch.Tensor:
    """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`.

    Parameters
    ----------
    matrix : torch.Tensor
        Square matrix to rescale.
    target_radius : float
        Desired largest absolute eigenvalue.

    Returns
    -------
    torch.Tensor
        The rescaled matrix (new tensor).
    """
    if not np.isfinite(target_radius) or target_radius < 0:
        raise ValueError("target_radius must be finite and non-negative.")
    current_radius = estimate_spectral_radius(matrix)

    if current_radius > 0.0:
        # Normalize before multiplying: target/current may overflow in the
        # matrix dtype even when the normalized matrix is representable.
        if matrix.layout == torch.sparse_csr:
            matrix = matrix.clone()
            matrix.values().div_(current_radius).mul_(target_radius)
        else:
            matrix = (matrix / current_radius) * target_radius
    elif target_radius > 0.0:
        # A nilpotent (all-eigenvalues-zero, e.g. the pure ``delay_line``) or
        # all-zero matrix cannot be rescaled to a nonzero radius — scaling a zero
        # spectrum leaves it zero. Warn rather than silently ignore the request,
        # so ``ESNLayer(topology="delay_line", spectral_radius=0.9)`` does not look
        # like it took effect. Control the scale through the topology's own weight
        # parameter instead.
        warnings.warn(
            f"spectral_radius={target_radius:g} was requested but the recurrent "
            f"matrix has a zero spectral radius (nilpotent or all-zero, e.g. the "
            f"'delay_line' / 'zeros' topologies); it cannot be rescaled to a nonzero "
            f"radius and is left unchanged. Set the scale via the topology's weight "
            f"parameter instead.",
            RuntimeWarning,
            stacklevel=2,
        )

    return matrix

show_topologies

show_topologies(name: str | None = None) -> list[str] | None

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

RETURNS DESCRIPTION
list of str or None

When name is None, returns the sorted list of registered topology names (in addition to printing them). When name is provided, returns None after printing the parameter table.

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
def show_topologies(name: str | None = None) -> list[str] | None:
    """
    Show available topologies or details for a specific topology.

    Parameters
    ----------
    name : str, optional
        Name of topology to inspect. If None, prints all
        registered topology names *and* returns them as a list.

    Returns
    -------
    list of str or None
        When `name is None`, returns the sorted list of registered
        topology names (in addition to printing them).  When `name` is
        provided, returns `None` after printing the parameter table.

    Raises
    ------
    ValueError
        If the specified topology name is not registered.
    """
    if name is None:
        names = sorted(_TOPOLOGY_REGISTRY)
        print("\nAvailable topologies:\n")
        for n in names:
            print(f"  - {n}")
        print(f"\nTotal: {len(names)}\n")
        return names

    if name not in _TOPOLOGY_REGISTRY:
        available = "\n".join(sorted(_TOPOLOGY_REGISTRY.keys()))
        raise ValueError(f"Unknown topology '{name}'.\nAvailable:\n{available}")

    builder_func, default_kwargs, wrapper_class, prescaled = _TOPOLOGY_REGISTRY[name]

    sig = inspect.signature(builder_func)

    kind = "graph" if wrapper_class is GraphTopology else "matrix"
    prescaled_note = ", pre-scaled" if prescaled else ""
    print(f"\nTopology: {name} ({kind}{prescaled_note})\n")
    print("Parameters:\n")

    for param_name, param in sig.parameters.items():
        if param_name == "n":
            continue

        # Type extraction
        annotation = param.annotation
        type_str = (
            "Any"
            if annotation is inspect.Parameter.empty
            else annotation if isinstance(annotation, str) else inspect.formatannotation(annotation)
        )

        # Default resolution
        if param_name in default_kwargs:
            default = default_kwargs[param_name]
        elif param.default is not inspect.Parameter.empty:
            default = param.default
        else:
            default = default_kwargs.get(param_name, "<required>")

        print(f"  - {param_name}")
        print(f"      type:    {type_str}")
        print(f"      default: {default}\n")

    return None

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 Normal(loc, scale) entries (reservoirpy mat_gen.normal).

UniformInputInitializer

Bounded Uniform(low, high) entries (reservoirpy mat_gen.uniform).

BernoulliInputInitializer

Bernoulli ±1 signs with density (reservoirpy mat_gen.bernoulli).

PseudoDiagonalInitializer

Structured block-diagonal pattern.

ChebyshevInitializer

Deterministic chaotic initialization.

LogisticMappingInitializer

Deterministic logistic-map initialization (RC.jl logistic_mapping).

MinimalInputInitializer

Rodan & Tiňo minimal-complexity dense input (RC.jl minimal_init).

WeightedInputInitializer

Block-diagonal random input (RC.jl weighted_init).

WeightedMinimalInitializer

Block-diagonal constant-magnitude input (RC.jl weighted_minimal).

InformedInputInitializer

State/model split for hybrid ESNs (RC.jl informed_init).

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 by s as 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 with s.

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. None (the default) applies no scaling. A float s scales the matrix's magnitude statistic linearly (input_scaling=0.5 halves it).

TYPE: float DEFAULT: None

connectivity

Fraction of nonzero entries to keep per column, in (0, 1]. None (the default) leaves the produced sparsity pattern untouched.

TYPE: float DEFAULT: None

seed

Reproducibility seed for any subclass randomness (the uniform/binary draws of the random initializers) and the connectivity mask. Accepts a plain int, a torch.Generator (whose initial_seed() is used so a generator and the equivalent int agree), or None (defer to the global RNG). The torch-native random initializers draw on the target tensor's device via _torch_generator_for, so the same seed is reproducible per device — including on CUDA.

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

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
def __init__(
    self,
    input_scaling: float | None = None,
    connectivity: float | None = None,
    seed: SeedLike = None,
) -> None:
    """Store and validate the shared scaling/connectivity parameters."""
    self.input_scaling = _validate_input_scaling(input_scaling)
    self.connectivity = _validate_connectivity(connectivity)
    self.seed = seed

initialize abstractmethod

initialize(weight: Tensor, **kwargs: Any) -> Tensor

Initialize a weight tensor.

PARAMETER DESCRIPTION
weight

2D tensor of shape (reservoir_size, input_size) to initialize. Modified in-place.

TYPE: Tensor

**kwargs

Per-call keyword overrides. The recognized contract parameters — input_scaling and connectivity — override the bound attributes for this call only (see the Per-call overrides section of InputFeedbackInitializer); specific initializers may recognize additional keys. Unrecognized keys are ignored. Implementations honor the overrides by forwarding **kwargs into _apply_scaling / _apply_connectivity.

TYPE: Any DEFAULT: {}

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
@abstractmethod
def initialize(self, weight: torch.Tensor, **kwargs: Any) -> torch.Tensor:
    """
    Initialize a weight tensor.

    Parameters
    ----------
    weight : torch.Tensor
        2D tensor of shape `(reservoir_size, input_size)` to initialize.
        Modified in-place.
    **kwargs
        Per-call keyword overrides. The recognized contract parameters —
        `input_scaling` and `connectivity` — override the bound
        attributes *for this call only* (see the **Per-call overrides**
        section of `InputFeedbackInitializer`); specific
        initializers may recognize additional keys. Unrecognized keys are
        ignored. Implementations honor the overrides by forwarding
        `**kwargs` into `_apply_scaling` /
        `_apply_connectivity`.

    Returns
    -------
    torch.Tensor
        The initialized weight tensor (same as input, modified in-place).
    """
    pass

FunctionInitializer

FunctionInitializer(fn: Callable, **kwargs: Any)

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:

  1. Build style — fn(rows, cols, **kwargs) returning a (rows, cols) array-like (torch.Tensor or numpy.ndarray).
  2. In-place style — fn(tensor, **kwargs) mutating a tensor in place, e.g. any torch.nn.init.*_ function.
PARAMETER DESCRIPTION
fn

The matrix-building function (build style or in-place style).

TYPE: callable

**kwargs

Keyword arguments bound to the function.

TYPE: Any DEFAULT: {}

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
def __init__(self, fn: Callable, **kwargs: Any) -> None:
    self.fn = fn
    self.kwargs = kwargs
    self._generator_seed = _pop_generator_seed(fn, self.kwargs)

initialize

initialize(weight: Tensor, **kwargs: Any) -> Tensor

Initialize a rectangular weight tensor from the wrapped callable.

PARAMETER DESCRIPTION
weight

2D tensor of shape (rows, cols) to initialize. Modified in-place.

TYPE: Tensor

**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 resdag.init.input_feedback.InputFeedbackInitializer.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION
Tensor

The initialized weight tensor (same as input, modified in-place).

RAISES DESCRIPTION
ValueError

If weight is not 2-D, if the callable matches neither calling convention, or if the built matrix has the wrong shape.

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
def initialize(self, weight: torch.Tensor, **kwargs: Any) -> torch.Tensor:
    """
    Initialize a rectangular weight tensor from the wrapped callable.

    Parameters
    ----------
    weight : torch.Tensor
        2D tensor of shape `(rows, cols)` to initialize. Modified
        in-place.
    **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
        `resdag.init.input_feedback.InputFeedbackInitializer`.

    Returns
    -------
    torch.Tensor
        The initialized weight tensor (same as input, modified in-place).

    Raises
    ------
    ValueError
        If `weight` is not 2-D, if the callable matches neither
        calling convention, or if the built matrix has the wrong shape.
    """
    if weight.ndim != 2:
        raise ValueError(f"Weight must be 2D, got shape {weight.shape}")

    rows, cols = weight.shape
    call_kwargs = {**self.kwargs, **kwargs}

    result = _call_matrix_builder(
        self.fn,
        weight,
        (rows, cols),
        call_kwargs,
        seed=_pop_generator_seed(self.fn, call_kwargs, getattr(self, "_generator_seed", None)),
    )
    matrix = _coerce_to_matrix(result, (rows, cols), weight.device, weight.dtype)

    with torch.no_grad():
        weight.copy_(matrix)

    return weight

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

  1. state_size = in_size - model_in_size (must be > 0).
  2. num_for_state = floor(reservoir_size * gamma) reservoir rows receive a single random connection to a randomly chosen state column [0, state_size).
  3. 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 model_in_size). The weight's in_features must exceed this so state_size > 0. Required — the bare-name registry default is None and raises at initialize time if left unset.

TYPE: int DEFAULT: None

gamma

Fraction of reservoir units wired to the raw state block (RC.jl gamma). Must lie in [0, 1].

TYPE: float DEFAULT: 0.5

input_scaling

Half-width of the uniform draw for each connection: values land in [-input_scaling, input_scaling] (RC.jl scaling). Shared scaling-contract knob, so max|W| scales linearly with it.

TYPE: float DEFAULT: 0.1

seed

Reproducibility seed for the row/column choices and value draws. None draws fresh each call.

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

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 gamma is not in [0, 1], or model_in_size is negative.

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
def __init__(
    self,
    model_in_size: int | None = None,
    gamma: float = 0.5,
    input_scaling: float | None = 0.1,
    seed: int | None = None,
) -> None:
    """Initialize the InformedInputInitializer.

    Raises
    ------
    ValueError
        If `gamma` is not in `[0, 1]`, or `model_in_size` is negative.
    """
    super().__init__(input_scaling=input_scaling, seed=seed)
    if not (0.0 <= float(gamma) <= 1.0):
        raise ValueError(f"gamma must be in [0, 1]; got {gamma!r}.")
    if model_in_size is not None and model_in_size < 0:
        raise ValueError(f"model_in_size must be >= 0; got {model_in_size!r}.")
    self.model_in_size = model_in_size
    self.gamma = float(gamma)

initialize

initialize(weight: Tensor, **kwargs: Any) -> Tensor

Fill the informed (state/model split) input weight.

PARAMETER DESCRIPTION
weight

Weight tensor of shape (out_features, in_features).

TYPE: Tensor

**kwargs

Per-call keyword overrides. A recognized input_scaling key overrides the bound self.input_scaling for this call only (the shared per-call contract); other keys are ignored.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION
Tensor

The initialized weight tensor (modified in-place).

RAISES DESCRIPTION
ValueError

If model_in_size is unset, or in_features <= model_in_size (so state_size <= 0).

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
def initialize(self, weight: torch.Tensor, **kwargs: Any) -> torch.Tensor:
    """Fill the informed (state/model split) input weight.

    Parameters
    ----------
    weight : torch.Tensor
        Weight tensor of shape `(out_features, in_features)`.
    **kwargs
        Per-call keyword overrides. A recognized `input_scaling` key
        overrides the bound `self.input_scaling` for this call only (the
        shared per-call contract); other keys are ignored.

    Returns
    -------
    torch.Tensor
        The initialized weight tensor (modified in-place).

    Raises
    ------
    ValueError
        If `model_in_size` is unset, or `in_features <= model_in_size`
        (so `state_size <= 0`).
    """
    out_features, in_features = _resolve_shape(weight)
    device = weight.device
    dtype = weight.dtype
    compute_dtype = _numpy_compute_dtype(dtype)

    if self.model_in_size is None:
        raise ValueError(
            "InformedInputInitializer requires 'model_in_size'; pass it explicitly, "
            "e.g. get_input_feedback('informed_init', model_in_size=1)."
        )
    model_in_size = self.model_in_size
    state_size = in_features - model_in_size
    if state_size <= 0:
        raise ValueError(
            f"in_features ({in_features}) must be greater than model_in_size "
            f"({model_in_size}) so state_size > 0."
        )

    rng = create_rng(coerce_seed_to_int(self.seed))
    values = np.zeros((out_features, in_features), dtype=compute_dtype)

    num_for_state = int(np.floor(out_features * self.gamma))
    num_for_model = int(np.floor(out_features * (1.0 - self.gamma)))

    # Draw the per-call scaling for the ``[-scaling, scaling]`` value range so
    # a per-call ``input_scaling`` override is honored (RC.jl bakes the scale
    # into each entry rather than as a final uniform multiply, so it is
    # resolved here rather than via ``_apply_scaling``).
    scaling = self._resolve_input_scaling(kwargs)

    def zero_row_indices() -> np.ndarray:
        """Rows still entirely zero — candidates for a new connection."""
        return np.flatnonzero(~values.any(axis=1))

    def wire(count: int, col_low: int, col_high: int) -> None:
        """Wire `count` still-zero rows to a random column in `[col_low, col_high)`."""
        for _ in range(count):
            candidates = zero_row_indices()
            if candidates.size == 0:
                break
            row = int(rng.choice(candidates))
            col = int(rng.integers(col_low, col_high))
            # RC.jl: (rand - 0.5) * 2 * scaling -> uniform in [-scaling, scaling].
            draw = (rng.random() - 0.5) * 2.0
            values[row, col] = draw if scaling is None else draw * scaling

    wire(num_for_state, 0, state_size)
    wire(num_for_model, state_size, in_features)

    weight_data = torch.from_numpy(values).to(device=device, dtype=dtype)
    with torch.no_grad():
        weight.copy_(weight_data)
    return weight

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 column j (RC.jl is 1-indexed, so column j uses j + 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 amplitude).

TYPE: float DEFAULT: 0.3

sine_divisor

Divisor in the sine phase (RC.jl sine_divisor).

TYPE: float DEFAULT: 5.9

logistic_parameter

Growth rate r of the logistic recurrence (RC.jl logistic_parameter).

TYPE: float DEFAULT: 3.7

input_scaling

Uniform magnitude knob from the shared scaling contract. None (the default) leaves the raw logistic orbit; a float s multiplies every entry by s as the documented final transform.

TYPE: float DEFAULT: None

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
def __init__(
    self,
    amplitude: float = 0.3,
    sine_divisor: float = 5.9,
    logistic_parameter: float = 3.7,
    input_scaling: float | None = None,
) -> None:
    """Initialize the LogisticMappingInitializer."""
    super().__init__(input_scaling=input_scaling)
    self.amplitude = float(amplitude)
    self.sine_divisor = float(sine_divisor)
    self.logistic_parameter = float(logistic_parameter)

initialize

initialize(weight: Tensor, **kwargs: Any) -> Tensor

Initialize the weight via the logistic map.

PARAMETER DESCRIPTION
weight

Weight tensor of shape (out_features, in_features).

TYPE: Tensor

**kwargs

Per-call keyword overrides. A recognized input_scaling key overrides the bound self.input_scaling for this call only (the shared per-call contract); other keys are ignored.

TYPE: Any DEFAULT: {}

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
def initialize(self, weight: torch.Tensor, **kwargs: Any) -> torch.Tensor:
    """Initialize the weight via the logistic map.

    Parameters
    ----------
    weight : torch.Tensor
        Weight tensor of shape `(out_features, in_features)`.
    **kwargs
        Per-call keyword overrides. A recognized `input_scaling` key
        overrides the bound `self.input_scaling` for this call only (the
        shared per-call contract); other keys are ignored.

    Returns
    -------
    torch.Tensor
        The initialized weight tensor (modified in-place).
    """
    out_features, in_features = _resolve_shape(weight)
    device = weight.device
    dtype = weight.dtype
    compute_dtype = _numpy_compute_dtype(dtype)

    values = np.zeros((out_features, in_features), dtype=compute_dtype)

    # First row: sine seed. RC.jl is 1-indexed, so column j uses (j + 1).
    cols = np.arange(1, in_features + 1, dtype=compute_dtype)
    values[0, :] = self.amplitude * np.sin(cols * np.pi / (self.sine_divisor * in_features))

    # Row-wise logistic recurrence.
    for i in range(1, out_features):
        prev = values[i - 1, :]
        values[i, :] = self.logistic_parameter * prev * (1.0 - prev)

    # Forward ``**kwargs`` so a per-call ``input_scaling`` override wins.
    values = self._apply_scaling(values, **kwargs)

    weight_data = torch.from_numpy(values).to(device=device, dtype=dtype)
    with torch.no_grad():
        weight.copy_(weight_data)
    return weight

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

  1. Fill an (reservoir_size, in_size) matrix with the constant weight.
  2. Apply the sign_rule in RC.jl's column-major traversal order.

Sign rules (RC.jl sampling_type):

  • "bernoulli" (default) — each entry keeps its + sign with probability positive_prob and is negated otherwise (RC.jl bernoulli_sample!). This is the RC.jl default. Requires a seed for reproducibility.
  • "irrational" — deterministic: an entry is negated when the corresponding decimal digit of pi (offset by start) is odd (RC.jl irrational_sample!). Fully reproducible, no RNG.
  • "regular" — deterministic: every strides-th entry (in flat column-major order) is negated (RC.jl _regular_sample!).
  • "none" — leave every sign positive (RC.jl no_sample).
PARAMETER DESCRIPTION
weight

The single magnitude assigned to every input weight (RC.jl weight).

TYPE: float DEFAULT: 0.1

sign_rule

The sign-assignment rule (RC.jl sampling_type without the _sample! suffix).

TYPE: (bernoulli, irrational, regular, none) DEFAULT: "bernoulli"

positive_prob

Probability an entry stays positive under sign_rule="bernoulli" (RC.jl positive_prob).

TYPE: float DEFAULT: 0.5

start

First pi-digit offset under sign_rule="irrational" (RC.jl start).

TYPE: int DEFAULT: 1

strides

Stride under sign_rule="regular"; every strides-th flat entry is negated (RC.jl strides).

TYPE: int DEFAULT: 2

input_scaling

Uniform magnitude knob from the shared scaling contract (see resdag.init.input_feedback.InputFeedbackInitializer). None (the default) leaves entries at magnitude weight; a float s multiplies every entry by s, so max|W| scales linearly with s (input_scaling=0.5 halves it). Applied on top of weight.

TYPE: float DEFAULT: None

seed

Reproducibility seed for the "bernoulli" sign draw. Ignored by the deterministic rules. None draws fresh each call.

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

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
def __init__(
    self,
    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,
) -> None:
    """Initialize the MinimalInputInitializer."""
    super().__init__(input_scaling=input_scaling, seed=seed)
    self.weight = float(weight)
    self.sign_rule = sign_rule
    self.positive_prob = float(positive_prob)
    self.start = int(start)
    self.strides = int(strides)

initialize

initialize(weight: Tensor, **kwargs: Any) -> Tensor

Initialize a dense constant-magnitude weight with signed entries.

PARAMETER DESCRIPTION
weight

Weight tensor of shape (out_features, in_features).

TYPE: Tensor

**kwargs

Per-call keyword overrides. A recognized input_scaling key overrides the bound self.input_scaling for this call only (the shared per-call contract); other keys are ignored.

TYPE: Any DEFAULT: {}

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
def initialize(self, weight: torch.Tensor, **kwargs: Any) -> torch.Tensor:
    """Initialize a dense constant-magnitude weight with signed entries.

    Parameters
    ----------
    weight : torch.Tensor
        Weight tensor of shape `(out_features, in_features)`.
    **kwargs
        Per-call keyword overrides. A recognized `input_scaling` key
        overrides the bound `self.input_scaling` for this call only (the
        shared per-call contract); other keys are ignored.

    Returns
    -------
    torch.Tensor
        The initialized weight tensor (modified in-place).
    """
    out_features, in_features = _resolve_shape(weight)
    device = weight.device
    dtype = weight.dtype
    compute_dtype = _numpy_compute_dtype(dtype)

    rng = create_rng(coerce_seed_to_int(self.seed))
    signs = build_sign_matrix(
        out_features,
        in_features,
        self.sign_rule,
        positive_prob=self.positive_prob,
        start=self.start,
        strides=self.strides,
        rng=rng,
    )

    # Dense constant magnitude, then per-entry sign.
    values = (self.weight * signs).astype(compute_dtype)

    # Apply the shared uniform scaling contract as the documented final
    # transform. Forward ``**kwargs`` so a per-call ``input_scaling`` override
    # wins over the bound value.
    values = self._apply_scaling(values, **kwargs)

    weight_data = torch.from_numpy(values).to(device=device, dtype=dtype)
    with torch.no_grad():
        weight.copy_(weight_data)
    return weight

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 +1 (it is -1 with probability 1 - p). Must lie in [0, 1]. Defaults to 0.5 (a balanced, zero-mean sign matrix).

TYPE: float DEFAULT: 0.5

connectivity

Density knob from the shared scaling contract (see resdag.init.input_feedback.InputFeedbackInitializer): the fraction of nonzero entries kept per column (input channel), in (0, 1]. None (the default) leaves the dense ±1 matrix untouched; connectivity=0.1 keeps ~10% of each column's signs (at least one), zeroing the rest. The kept fraction is statistically exact: round(connectivity * reservoir_size) entries per column.

TYPE: float DEFAULT: None

input_scaling

Uniform magnitude knob from the shared scaling contract. None (the default) leaves entries in {-1, +1}; a float s multiplies every entry by s (entries become {-s, +s}), so max|W| scales linearly with s (input_scaling=0.5 halves it).

TYPE: float DEFAULT: None

seed

Reproducibility seed for the Bernoulli draw and the connectivity mask. Accepts a plain int, a torch.Generator (whose initial_seed() is used, so a generator and the equivalent int agree), or None (defer to torch's global RNG). The value draw is device-native: it happens directly on the target weight's device via a torch generator, so the same seed is reproducible per device (CPU and CUDA each reproduce, though their RNG streams differ from each other).

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

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
def __init__(
    self,
    p: float = 0.5,
    connectivity: float | None = None,
    input_scaling: float | None = None,
    seed: SeedLike = None,
) -> None:
    """Initialize the BernoulliInputInitializer."""
    super().__init__(
        input_scaling=input_scaling,
        connectivity=connectivity,
        seed=seed,
    )
    p = float(p)
    if not (0.0 <= p <= 1.0):
        raise ValueError(f"p must be in [0, 1]; got {p!r}.")
    self.p = p

initialize

initialize(weight: Tensor, **kwargs: Any) -> Tensor

Initialize weight with Bernoulli ±1 entries.

PARAMETER DESCRIPTION
weight

Weight tensor of shape (out_features, in_features). Modified in-place.

TYPE: Tensor

**kwargs

Per-call keyword overrides. Recognized input_scaling and connectivity keys override the bound attributes for this call only (the shared per-call contract — see resdag.init.input_feedback.InputFeedbackInitializer); other keys are ignored.

TYPE: Any DEFAULT: {}

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
def initialize(self, weight: torch.Tensor, **kwargs: Any) -> torch.Tensor:
    """Initialize `weight` with Bernoulli `±1` entries.

    Parameters
    ----------
    weight : torch.Tensor
        Weight tensor of shape `(out_features, in_features)`. Modified
        in-place.
    **kwargs
        Per-call keyword overrides. Recognized `input_scaling` and
        `connectivity` keys override the bound attributes for this call
        only (the shared per-call contract — see
        `resdag.init.input_feedback.InputFeedbackInitializer`);
        other keys are ignored.

    Returns
    -------
    torch.Tensor
        The initialized weight tensor (same object, modified in-place).
    """
    out_features, in_features = _resolve_shape(weight)
    device = weight.device
    dtype = weight.dtype

    generator = self._torch_generator_for(device)

    # Draw uniform [0, 1) on-device, then threshold at ``1 - p`` so that an
    # entry is +1 with probability ``p`` and -1 otherwise.
    draws = torch.empty(out_features, in_features, device=device, dtype=dtype)
    draws.uniform_(0.0, 1.0, generator=generator)
    values = torch.where(
        draws < self.p,
        torch.ones_like(draws),
        -torch.ones_like(draws),
    )

    # Apply the shared connectivity then scaling contract, in that order
    # (zeroing then scaling is identical either way; this matches the base
    # class's documented composition ``_apply_scaling(_apply_connectivity)``).
    # Forward ``**kwargs`` so per-call ``connectivity`` / ``input_scaling``
    # overrides win over the bound values.
    values = self._apply_connectivity(values, **kwargs)
    values = self._apply_scaling(values, **kwargs)

    with torch.no_grad():
        weight.copy_(values)

    return weight

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 resdag.init.input_feedback.InputFeedbackInitializer). None (the default) leaves entries in {-1, +1}; a float s multiplies every entry by s (entries become {-s, +s}), so max|W| scales linearly with s (input_scaling=0.5 halves it).

TYPE: float DEFAULT: None

balance_global

When rows is odd, enforce near-equal global count of +1 vs -1 column-sums by flipping full columns.

TYPE: bool DEFAULT: True

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

seed

Unused (kept for API compatibility). The initializer is fully deterministic.

TYPE: int DEFAULT: None

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
def __init__(
    self,
    input_scaling: float | None = None,
    balance_global: bool = True,
    step: int | None = None,
    seed: int | None = None,  # Unused, for API consistency
) -> None:
    """Initialize the BinaryBalancedInitializer."""
    super().__init__(input_scaling=input_scaling, seed=seed)
    self.balance_global = balance_global
    self.step = step

initialize

initialize(weight: Tensor, **kwargs: Any) -> Tensor

Initialize weight tensor with binary balanced structure.

PARAMETER DESCRIPTION
weight

Weight tensor of shape (out_features, in_features)

TYPE: Tensor

**kwargs

Per-call keyword overrides. A recognized input_scaling key overrides the bound self.input_scaling for this call only (the shared per-call contract — see resdag.init.input_feedback.InputFeedbackInitializer); other keys are ignored.

TYPE: Any DEFAULT: {}

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
def initialize(self, weight: torch.Tensor, **kwargs: Any) -> torch.Tensor:
    """Initialize weight tensor with binary balanced structure.

    Parameters
    ----------
    weight : torch.Tensor
        Weight tensor of shape (out_features, in_features)
    **kwargs
        Per-call keyword overrides. A recognized `input_scaling` key
        overrides the bound `self.input_scaling` for this call only (the
        shared per-call contract — see
        `resdag.init.input_feedback.InputFeedbackInitializer`);
        other keys are ignored.

    Returns
    -------
    torch.Tensor
        Initialized weight tensor
    """
    out_features, in_features = _resolve_shape(weight)
    device = weight.device
    dtype = weight.dtype
    compute_dtype = _numpy_compute_dtype(dtype)

    rows, cols = out_features, in_features

    if rows == 0 or cols == 0:
        weight.zero_()
        return weight

    # Work with even row count
    n_work = rows if (rows % 2 == 0) else rows + 1

    # Build Hadamard matrix
    L = self._next_pow2(max(n_work, cols + 1, 2))
    H = self._hadamard(L)

    s = self._choose_step(L, self.step)
    idxs = [1 + (j * s) % (L - 1) for j in range(cols)]  # Exclude DC column

    Vw = H[:n_work, idxs].copy()

    # Balance each column to sum zero
    self._balance_columns_zero_sum(Vw)

    # If rows is even, done; else delete one row and optionally balance
    if n_work == rows:
        V = Vw
    else:
        V = self._delete_least_bias_row(Vw)
        if self.balance_global:
            self._balance_global_column_counts(V)

    # Build at the target precision so a non-float32-representable
    # input_scaling survives a float64 weight intact.
    values = V.astype(compute_dtype)

    # Apply the shared uniform scaling contract as the documented final
    # transform. Forward ``**kwargs`` so a per-call ``input_scaling`` override
    # wins over the bound value.
    values = self._apply_scaling(values, **kwargs)

    # Convert to tensor and copy to weight
    weight_data = torch.from_numpy(values).to(device=device, dtype=dtype)

    with torch.no_grad():
        weight.copy_(weight_data)

    return weight

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 in_features). None (the default) infers it from the weight's column count at initialize time, so the bare-name registry path get_input_feedback("chain_of_neurons_input") works. When an explicit value is given it is validated against the weight shape.

TYPE: int DEFAULT: None

weights

Either a single float (same weight for all input→chain pairs) or a sequence of floats (one weight per input/chain).

TYPE: float or Sequence[float] DEFAULT: 1.0

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 features is given but < 1.

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
def __init__(
    self,
    features: int | None = None,
    weights: float | Sequence[float] = 1.0,
):
    """Initialize the ChainOfNeuronsInputInitializer.

    Raises
    ------
    ValueError
        If `features` is given but `< 1`.
    """
    if features is not None and features < 1:
        raise ValueError(f"'features' must be >= 1, got {features}.")
    self.features = features
    self.weights = weights

initialize

initialize(weight: Tensor, **kwargs: Any) -> Tensor

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 features is None it is inferred from this column count)

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Initialized weight tensor

RAISES DESCRIPTION
ValueError

If an explicit features does not equal in_features, or units is not a multiple of the number of chains.

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
def initialize(self, weight: torch.Tensor, **kwargs: Any) -> torch.Tensor:
    """Initialize weight tensor for chain-of-neurons topology.

    Parameters
    ----------
    weight : torch.Tensor
        Weight tensor of shape (out_features, in_features)
        out_features = reservoir_size (units)
        in_features = num_inputs (must equal features; when `features` is
        `None` it is inferred from this column count)

    Returns
    -------
    torch.Tensor
        Initialized weight tensor

    Raises
    ------
    ValueError
        If an explicit `features` does not equal `in_features`, or
        `units` is not a multiple of the number of chains.
    """
    units, input_dim = _resolve_shape(weight)
    device = weight.device
    dtype = weight.dtype
    compute_dtype = _numpy_compute_dtype(dtype)

    # ``features`` equals the number of chains, which equals the weight's
    # column count (one input per chain). Infer it from the weight when the
    # caller left it unset; otherwise validate the explicit value matches.
    if self.features is None:
        features = input_dim
    else:
        features = self.features
        if input_dim != features:
            raise ValueError(
                f"input_dim ({input_dim}) must equal 'features' ({features}) "
                "to have one input per chain."
            )

    if units % features != 0:
        raise ValueError(
            f"Number of units ({units}) must be a multiple of 'features' "
            f"({features}) to align chains with inputs."
        )

    # Build at the target precision so non-float32-representable per-input
    # weights survive a float64 weight intact.
    values = np.zeros((units, input_dim), dtype=compute_dtype)

    # Resolve per-input weights
    if isinstance(self.weights, (list, tuple, np.ndarray)):
        if len(self.weights) != input_dim:
            raise ValueError(
                "When 'weights' is a sequence, its length must equal input_dim; "
                f"got len(weights)={len(self.weights)}, input_dim={input_dim}."
            )
        in_weights = [float(w) for w in self.weights]
    else:
        # Reached only when ``self.weights`` is not a list/tuple/ndarray, i.e.
        # the scalar branch of the ``float | Sequence[float]`` union; cast for mypy.
        w = float(cast(float, self.weights))
        in_weights = [w] * input_dim

    block_len = units // features

    # Deterministic: input i → first unit of chain i
    for i in range(input_dim):
        start = i * block_len
        values[start, i] = in_weights[i]

    # Convert to tensor and copy to weight
    weight_data = torch.from_numpy(values).to(device=device, dtype=dtype)

    with torch.no_grad():
        weight.copy_(weight_data)

    return weight

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: float DEFAULT: 0.3

q

Parameter controlling the initial sinusoidal distribution.

TYPE: float DEFAULT: 5.9

k

Control parameter of the Chebyshev map. Must be in (2, 4) for chaotic behavior.

TYPE: float DEFAULT: 3.8

input_scaling

Uniform magnitude knob from the shared scaling contract (see resdag.init.input_feedback.InputFeedbackInitializer). None (the default) applies no scaling; a float s multiplies every entry by s as the documented final transform, so max|W| scales linearly with s (input_scaling=0.5 halves it).

TYPE: float DEFAULT: None

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
def __init__(
    self,
    p: float = 0.3,
    q: float = 5.9,
    k: float = 3.8,
    input_scaling: float | None = None,
) -> None:
    """Initialize the ChebyshevInitializer."""
    if not (2.0 < k < 4.0):
        raise ValueError(f"Parameter k={k} must be in range (2, 4) for chaotic behavior")

    super().__init__(input_scaling=input_scaling)
    self.p = p
    self.q = q
    self.k = k

initialize

initialize(weight: Tensor, **kwargs: Any) -> Tensor

Initialize weight tensor using Chebyshev mapping.

PARAMETER DESCRIPTION
weight

Weight tensor of shape (out_features, in_features)

TYPE: Tensor

**kwargs

Per-call keyword overrides. A recognized input_scaling key overrides the bound self.input_scaling for this call only (the shared per-call contract — see resdag.init.input_feedback.InputFeedbackInitializer); other keys are ignored.

TYPE: Any DEFAULT: {}

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
def initialize(self, weight: torch.Tensor, **kwargs: Any) -> torch.Tensor:
    """Initialize weight tensor using Chebyshev mapping.

    Parameters
    ----------
    weight : torch.Tensor
        Weight tensor of shape (out_features, in_features)
    **kwargs
        Per-call keyword overrides. A recognized `input_scaling` key
        overrides the bound `self.input_scaling` for this call only (the
        shared per-call contract — see
        `resdag.init.input_feedback.InputFeedbackInitializer`);
        other keys are ignored.

    Returns
    -------
    torch.Tensor
        Initialized weight tensor with Chebyshev structure
    """
    out_features, in_features = _resolve_shape(weight)
    device = weight.device
    dtype = weight.dtype
    compute_dtype = _numpy_compute_dtype(dtype)

    # Initialize matrix at the target precision so float64 weights are not
    # silently truncated to float32 before the final widening copy.
    values = np.zeros((out_features, in_features), dtype=compute_dtype)

    # First column: sinusoidal initialization
    row_indices = np.arange(1, out_features + 1, dtype=compute_dtype)
    values[:, 0] = self.p * np.sin((row_indices / (out_features + 1)) * (np.pi / self.q))

    # Apply Chebyshev recurrence column-wise
    for j in range(1, in_features):
        values[:, j] = np.cos(self.k * np.arccos(np.clip(values[:, j - 1], -1.0, 1.0)))

    # Normalize each column to unit peak amplitude so the small-amplitude seed
    # column (~|p|) is no longer ~1/p weaker than the chaotic columns (~1). This
    # makes the magnitude statistic ``max|W|`` uniform across feedback dimensions
    # before the scaling contract applies. Columns that are entirely zero (e.g. a
    # degenerate p=0 seed) are left untouched to avoid dividing by zero.
    col_peak = np.max(np.abs(values), axis=0, keepdims=True)
    np.divide(values, col_peak, out=values, where=col_peak > 0.0)

    # Apply the shared uniform scaling contract as the documented final
    # transform. Forward ``**kwargs`` so a per-call ``input_scaling`` override
    # wins over the bound value.
    values = self._apply_scaling(values, **kwargs)

    # Convert to tensor and copy to weight
    weight_data = torch.from_numpy(values).to(device=device, dtype=dtype)

    with torch.no_grad():
        weight.copy_(weight_data)

    return weight

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 resdag.init.input_feedback.InputFeedbackInitializer). None (the default) leaves entries in {-1, +1}; a float s multiplies every entry by s (entries become {-s, +s}), so max|W| scales linearly with s (input_scaling=0.5 halves it).

TYPE: float DEFAULT: None

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
def __init__(self, input_scaling: float | None = None) -> None:
    """Initialize the ChessboardInitializer."""
    super().__init__(input_scaling=input_scaling)

initialize

initialize(weight: Tensor, **kwargs: Any) -> Tensor

Initialize weight tensor with chessboard pattern.

PARAMETER DESCRIPTION
weight

Weight tensor of shape (out_features, in_features)

TYPE: Tensor

**kwargs

Per-call keyword overrides. A recognized input_scaling key overrides the bound self.input_scaling for this call only (the shared per-call contract — see resdag.init.input_feedback.InputFeedbackInitializer); other keys are ignored.

TYPE: Any DEFAULT: {}

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
def initialize(self, weight: torch.Tensor, **kwargs: Any) -> torch.Tensor:
    """Initialize weight tensor with chessboard pattern.

    Parameters
    ----------
    weight : torch.Tensor
        Weight tensor of shape (out_features, in_features)
    **kwargs
        Per-call keyword overrides. A recognized `input_scaling` key
        overrides the bound `self.input_scaling` for this call only (the
        shared per-call contract — see
        `resdag.init.input_feedback.InputFeedbackInitializer`);
        other keys are ignored.

    Returns
    -------
    torch.Tensor
        Initialized weight tensor with chessboard pattern
    """
    out_features, in_features = _resolve_shape(weight)
    device = weight.device
    dtype = weight.dtype
    compute_dtype = _numpy_compute_dtype(dtype)

    # Create chessboard pattern at the target precision so any scaling that
    # is not float32-representable survives a float64 weight intact.
    i = np.arange(out_features)[:, None]
    j = np.arange(in_features)[None, :]
    values = ((-1.0) ** (i + j)).astype(compute_dtype)

    # Apply the shared uniform scaling contract as the documented final
    # transform. Forward ``**kwargs`` so a per-call ``input_scaling`` override
    # wins over the bound value.
    values = self._apply_scaling(values, **kwargs)

    # Convert to tensor and copy to weight
    weight_data = torch.from_numpy(values).to(device=device, dtype=dtype)

    with torch.no_grad():
        weight.copy_(weight_data)

    return weight

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

C

Number of cycle (core) nodes. If provided, c is ignored.

TYPE: int DEFAULT: None

draw_width

Half-width of the uniform draw U[-draw_width, draw_width] for each active connection.

TYPE: float DEFAULT: 1.0

input_scaling

Uniform multiplicative scaling applied as the final transform. None (the default) applies no scaling. input_scaling=0.5 halves every weight, so max|W| is halved.

TYPE: float DEFAULT: None

connectivity

Unused by this initializer: dendrocycle defines its own (core-only) connectivity pattern, so this knob is accepted for API uniformity but ignored. Always None in practice.

TYPE: float DEFAULT: None

seed

Random seed for reproducibility.

TYPE: int DEFAULT: None

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
def __init__(
    self,
    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,
) -> None:
    """Initialize the DendrocycleInputInitializer."""
    super().__init__(input_scaling=input_scaling, connectivity=connectivity, seed=seed)
    if (c is None) == (C is None):
        raise ValueError("Provide exactly one of c or C.")
    if not (np.isfinite(draw_width) and draw_width > 0):
        raise ValueError("draw_width must be a positive finite float.")
    self.c = c
    self.C = C
    self.draw_width = float(draw_width)

initialize

initialize(weight: Tensor, **kwargs: Any) -> Tensor

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

**kwargs

Per-call keyword overrides. A recognized input_scaling key overrides the bound self.input_scaling for this call only (the shared per-call contract — see resdag.init.input_feedback.InputFeedbackInitializer); other keys are ignored. connectivity is not honored here (this initializer defines its own core-only pattern).

TYPE: Any DEFAULT: {}

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
def initialize(self, weight: torch.Tensor, **kwargs: Any) -> torch.Tensor:
    """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.

    Parameters
    ----------
    weight : torch.Tensor
        Weight tensor of shape (out_features, in_features)
        out_features = reservoir_size (N)
        in_features = num_inputs (M)
    **kwargs
        Per-call keyword overrides. A recognized `input_scaling` key
        overrides the bound `self.input_scaling` for this call only (the
        shared per-call contract — see
        `resdag.init.input_feedback.InputFeedbackInitializer`);
        other keys are ignored. `connectivity` is not honored here (this
        initializer defines its own core-only pattern).

    Returns
    -------
    torch.Tensor
        Initialized weight tensor (only core nodes have non-zero weights)
    """
    N, M = _resolve_shape(weight)
    device = weight.device
    dtype = weight.dtype
    compute_dtype = _numpy_compute_dtype(dtype)

    rng = create_rng(coerce_seed_to_int(self.seed))

    C = self.C
    if C is None:
        # __init__ enforces exactly one of c/C is set, so C is None ⇒ c is not None.
        assert self.c is not None
        if not (0 < self.c <= 1):
            raise ValueError("c must be in (0, 1].")
        C = max(1, int(round(self.c * N)))
    if not (1 <= C <= N):
        raise ValueError("C must be in [1, N].")

    # Build at the target precision so the float64 ``rng.uniform`` draws are
    # not truncated to float32 in a float64 weight.
    values = np.zeros((N, M), dtype=compute_dtype)

    # Case 1: fewer inputs than cores
    if M <= C:
        mapping = [int(np.floor(i * M / C)) for i in range(C)]
        for core_idx, input_idx in enumerate(mapping):
            values[core_idx, input_idx] = rng.uniform(-self.draw_width, self.draw_width)
    # Case 2: more inputs than cores
    else:
        mapping = [int(np.floor(i * C / M)) for i in range(M)]
        for input_idx, core_idx in enumerate(mapping):
            values[core_idx, input_idx] = rng.uniform(-self.draw_width, self.draw_width)

    # Apply the shared uniform scaling contract as the documented final
    # transform. Forward ``**kwargs`` so a per-call ``input_scaling`` override
    # wins over the bound value.
    values = self._apply_scaling(values, **kwargs)

    # Convert to tensor and copy to weight
    weight_data = torch.from_numpy(values).to(device=device, dtype=dtype)

    with torch.no_grad():
        weight.copy_(weight_data)

    return weight

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

TYPE: float DEFAULT: 0.0

scale

Standard deviation of the Gaussian draw (must be non-negative). Defaults to 1.0.

TYPE: float DEFAULT: 1.0

connectivity

Density knob from the shared scaling contract (see resdag.init.input_feedback.InputFeedbackInitializer): the fraction of nonzero entries kept per column (input channel), in (0, 1]. None (the default) leaves the dense matrix untouched; connectivity=0.1 keeps ~10% of each column's entries (at least one), zeroing the rest. The kept fraction is statistically exact: round(connectivity * reservoir_size) entries per column.

TYPE: float DEFAULT: None

input_scaling

Uniform magnitude knob from the shared scaling contract. None (the default) applies no scaling; a float s multiplies every entry by s, so max|W| scales linearly with s (input_scaling=0.5 halves it).

TYPE: float DEFAULT: None

seed

Reproducibility seed for the Gaussian draw and the connectivity mask. Accepts a plain int, a torch.Generator (whose initial_seed() is used, so a generator and the equivalent int agree), or None (defer to torch's global RNG). The value draw is device-native: it happens directly on the target weight's device via a torch generator, so the same seed is reproducible per device (CPU and CUDA each reproduce, though their RNG streams differ from each other).

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

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
def __init__(
    self,
    loc: float = 0.0,
    scale: float = 1.0,
    connectivity: float | None = None,
    input_scaling: float | None = None,
    seed: SeedLike = None,
) -> None:
    """Initialize the NormalInputInitializer."""
    super().__init__(
        input_scaling=input_scaling,
        connectivity=connectivity,
        seed=seed,
    )
    scale = float(scale)
    if scale < 0.0:
        raise ValueError(f"scale must be non-negative; got {scale!r}.")
    self.loc = float(loc)
    self.scale = scale

initialize

initialize(weight: Tensor, **kwargs: Any) -> Tensor

Initialize weight with Normal(loc, scale) entries.

PARAMETER DESCRIPTION
weight

Weight tensor of shape (out_features, in_features). Modified in-place.

TYPE: Tensor

**kwargs

Per-call keyword overrides. Recognized input_scaling and connectivity keys override the bound attributes for this call only (the shared per-call contract — see resdag.init.input_feedback.InputFeedbackInitializer); other keys are ignored.

TYPE: Any DEFAULT: {}

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
def initialize(self, weight: torch.Tensor, **kwargs: Any) -> torch.Tensor:
    """Initialize `weight` with `Normal(loc, scale)` entries.

    Parameters
    ----------
    weight : torch.Tensor
        Weight tensor of shape `(out_features, in_features)`. Modified
        in-place.
    **kwargs
        Per-call keyword overrides. Recognized `input_scaling` and
        `connectivity` keys override the bound attributes for this call
        only (the shared per-call contract — see
        `resdag.init.input_feedback.InputFeedbackInitializer`);
        other keys are ignored.

    Returns
    -------
    torch.Tensor
        The initialized weight tensor (same object, modified in-place).
    """
    out_features, in_features = _resolve_shape(weight)
    device = weight.device
    dtype = weight.dtype

    generator = self._torch_generator_for(device)

    # Draw Gaussian values directly on the target device.
    values = torch.empty(out_features, in_features, device=device, dtype=dtype)
    values.normal_(self.loc, self.scale, generator=generator)

    # Apply the shared connectivity then scaling contract, in that order
    # (zeroing then scaling is identical either way; this matches the base
    # class's documented composition ``_apply_scaling(_apply_connectivity)``).
    # Forward ``**kwargs`` so per-call ``connectivity`` / ``input_scaling``
    # overrides win over the bound values.
    values = self._apply_connectivity(values, **kwargs)
    values = self._apply_scaling(values, **kwargs)

    with torch.no_grad():
        weight.copy_(values)

    return weight

OppositeAnchorsInitializer

OppositeAnchorsInitializer(
    input_scaling: float | None = None, gain: float | None = None
)

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 1.0 when neither input_scaling nor the deprecated gain is given.

TYPE: float DEFAULT: None

gain

Deprecated alias for input_scaling (same meaning). Emits a DeprecationWarning; passing both input_scaling and gain raises.

TYPE: float DEFAULT: None

RAISES DESCRIPTION
ValueError

If the resolved scaling is not a positive finite float (at construction), if both input_scaling and gain are supplied, or if in_features > reservoir_size when initialize is called.

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
def __init__(
    self,
    input_scaling: float | None = None,
    gain: float | None = None,
) -> None:
    """Initialize the OppositeAnchorsInitializer."""
    resolved = _resolve_scaling_alias(input_scaling, gain, default=1.0)
    if resolved is None or not np.isfinite(resolved) or resolved <= 0:
        raise ValueError("input_scaling must be a positive finite float.")
    super().__init__(input_scaling=resolved)

gain property

gain: float | None

Deprecated alias for input_scaling.

initialize

initialize(weight: Tensor, **kwargs: Any) -> Tensor

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

**kwargs

Per-call keyword overrides. A recognized input_scaling key overrides the bound self.input_scaling (the per-channel L2-norm target) for this call only (the shared per-call contract — see resdag.init.input_feedback.InputFeedbackInitializer); other keys are ignored. The override must be a positive finite float (None is not accepted for this structured initializer).

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION
Tensor

Initialized weight tensor

RAISES DESCRIPTION
ValueError

If m or n is non-positive, if m > n (more input channels than ring nodes), which would force duplicate columns, or if a per-call input_scaling override is not a positive finite float.

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
def initialize(self, weight: torch.Tensor, **kwargs: Any) -> torch.Tensor:
    """Initialize weight tensor with opposite anchor pattern.

    Parameters
    ----------
    weight : torch.Tensor
        Weight tensor of shape (out_features, in_features)
        out_features = number of ring nodes (n)
        in_features = number of input channels (m)
    **kwargs
        Per-call keyword overrides. A recognized `input_scaling` key
        overrides the bound `self.input_scaling` (the per-channel L2-norm
        target) for this call only (the shared per-call contract — see
        `resdag.init.input_feedback.InputFeedbackInitializer`);
        other keys are ignored. The override must be a positive finite float
        (`None` is not accepted for this structured initializer).

    Returns
    -------
    torch.Tensor
        Initialized weight tensor

    Raises
    ------
    ValueError
        If `m` or `n` is non-positive, if `m > n` (more input channels
        than ring nodes), which would force duplicate columns, or if a
        per-call `input_scaling` override is not a positive finite float.
    """
    n, m = _resolve_shape(weight)  # n=ring nodes, m=input channels
    device = weight.device
    dtype = weight.dtype
    compute_dtype = _numpy_compute_dtype(dtype)

    if m <= 0 or n <= 0:
        raise ValueError(f"m and n must be positive; received: (m={m}, n={n})")

    if m > n:
        raise ValueError(
            "opposite_anchors requires in_features <= reservoir_size: the ring has "
            f"only n={n} nodes, so at most {n} channels can be assigned distinct "
            f"anchors, but received in_features={m}. Reduce in_features or grow the "
            "reservoir."
        )

    # Build at the target precision so input_scaling / sqrt(2) keeps full
    # precision in a float64 weight instead of being truncated to float32.
    values = np.zeros((n, m), dtype=compute_dtype)
    half = n // 2

    # ``input_scaling`` is the per-channel L2 norm target. Resolve the
    # effective value from the per-call ``**kwargs`` (a recognized
    # ``input_scaling`` key wins) with the bound value as fallback, so a
    # per-call override is honored. The bound value is never None (the
    # constructor resolves the alias and defaults it to 1.0); a per-call
    # override must likewise be a positive finite float for this structured
    # initializer.
    scaling_resolved = self._resolve_input_scaling(kwargs)
    if scaling_resolved is None or not np.isfinite(scaling_resolved) or scaling_resolved <= 0:
        raise ValueError("input_scaling must be a positive finite float.")
    scaling = float(scaling_resolved)

    # Special case: n == 1
    if n == 1:
        # All weight on the single node; |w| == per-channel L2 norm.
        values[0, :] = scaling
    else:
        # Spread the positive anchors evenly around the *full* ring so distinct
        # channels never collide while m <= n. The negative anchor is the
        # diametrically opposite node.
        j0 = np.round(np.arange(m) * n / m).astype(int) % n
        j1 = (j0 + half) % n

        # Two equal-magnitude entries per column -> per-channel L2 norm is
        # sqrt(2) * w, so w = scaling / sqrt(2) makes the norm equal scaling.
        w = scaling / np.sqrt(2.0)
        values[j0, np.arange(m)] = w
        values[j1, np.arange(m)] = -w  # Negative for bipolar pattern

    # Convert to tensor and copy to weight
    weight_data = torch.from_numpy(values).to(device=device, dtype=dtype)

    with torch.no_grad():
        weight.copy_(weight_data)

    return weight

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 resdag.init.input_feedback.InputFeedbackInitializer). None (the default) applies no scaling (nonzero entries stay in [-1, 1]); a float s multiplies every entry by s, so max|W| scales linearly with s (input_scaling=0.5 halves it).

TYPE: float DEFAULT: None

binarize

Whether to binarize weights to {-input_scaling, input_scaling} instead of uniform distribution.

TYPE: bool DEFAULT: False

seed

Random seed for reproducibility.

TYPE: int DEFAULT: None

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
def __init__(
    self,
    input_scaling: float | None = None,
    binarize: bool = False,
    seed: int | None = None,
) -> None:
    """Initialize the PseudoDiagonalInitializer."""
    super().__init__(input_scaling=input_scaling, seed=seed)
    self.binarize = binarize

initialize

initialize(weight: Tensor, **kwargs: Any) -> Tensor

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

**kwargs

Per-call keyword overrides. A recognized input_scaling key overrides the bound self.input_scaling for this call only (the shared per-call contract — see resdag.init.input_feedback.InputFeedbackInitializer); other keys are ignored.

TYPE: Any DEFAULT: {}

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
def initialize(self, weight: torch.Tensor, **kwargs: Any) -> torch.Tensor:
    """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.

    Parameters
    ----------
    weight : torch.Tensor
        Weight tensor of shape (out_features, in_features)
    **kwargs
        Per-call keyword overrides. A recognized `input_scaling` key
        overrides the bound `self.input_scaling` for this call only (the
        shared per-call contract — see
        `resdag.init.input_feedback.InputFeedbackInitializer`);
        other keys are ignored.

    Returns
    -------
    torch.Tensor
        Initialized weight tensor with block structure
    """
    out_features, in_features = _resolve_shape(weight)
    device = weight.device
    dtype = weight.dtype
    compute_dtype = _numpy_compute_dtype(dtype)

    rng = create_rng(coerce_seed_to_int(self.seed))

    # Create sparse block-diagonal structure at the target precision so that
    # the float64 ``rng.uniform`` draws are not truncated to float32.
    values = np.zeros((out_features, in_features), dtype=compute_dtype)

    # Case 1: out_features >= in_features (typical for reservoirs)
    # Each input feature gets a contiguous block of output neurons
    if out_features >= in_features:
        block_size = out_features // in_features
        remainder = out_features % in_features

        start_row = 0
        for col in range(in_features):
            # Determine block size for this column
            end_row = start_row + block_size + (1 if col < remainder else 0)

            # Fill this block
            block_values = rng.uniform(-1.0, 1.0, size=(end_row - start_row,))
            if self.binarize:
                block_values = np.sign(block_values)

            values[start_row:end_row, col] = block_values
            start_row = end_row

    # Case 2: out_features < in_features (rare case)
    # Each output neuron gets input from a contiguous block of input features
    else:
        block_size = in_features // out_features
        remainder = in_features % out_features

        start_col = 0
        for row in range(out_features):
            # Determine block size for this row
            end_col = start_col + block_size + (1 if row < remainder else 0)

            # Fill this block
            block_values = rng.uniform(-1.0, 1.0, size=(end_col - start_col,))
            if self.binarize:
                block_values = np.sign(block_values)

            values[row, start_col:end_col] = block_values
            start_col = end_col

    # Apply the shared uniform scaling contract as the documented final
    # transform. Forward ``**kwargs`` so a per-call ``input_scaling`` override
    # wins over the bound value.
    values = self._apply_scaling(values, **kwargs)

    # Convert to tensor and copy to weight
    weight_data = torch.from_numpy(values).to(device=device, dtype=dtype)

    with torch.no_grad():
        weight.copy_(weight_data)

    return weight

RandomBinaryInitializer

RandomBinaryInitializer(input_scaling: float | None = None, seed: SeedLike = None)

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 resdag.init.input_feedback.InputFeedbackInitializer). None (the default) leaves entries in {-1, +1}; a float s multiplies every entry by s (entries become {-s, +s}), so max|W| scales linearly with s (input_scaling=0.5 halves it).

TYPE: float DEFAULT: None

seed

Reproducibility seed for the binary draw. Accepts a plain int, a torch.Generator (whose initial_seed() is used), or None (defer to torch's global RNG). The draw is device-native: it happens directly on the target weight's device via a torch generator, so the same seed is reproducible per device (CPU and CUDA each reproduce, though their RNG streams differ from each other).

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

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
def __init__(
    self,
    input_scaling: float | None = None,
    seed: SeedLike = None,
) -> None:
    """Initialize the RandomBinaryInitializer."""
    super().__init__(input_scaling=input_scaling, seed=seed)

initialize

initialize(weight: Tensor, **kwargs: Any) -> Tensor

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

**kwargs

Per-call keyword overrides. A recognized input_scaling key overrides the bound self.input_scaling for this call only (the shared per-call contract — see resdag.init.input_feedback.InputFeedbackInitializer); other keys are ignored.

TYPE: Any DEFAULT: {}

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
def initialize(self, weight: torch.Tensor, **kwargs: Any) -> torch.Tensor:
    """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`).

    Parameters
    ----------
    weight : torch.Tensor
        Weight tensor of shape (out_features, in_features)
    **kwargs
        Per-call keyword overrides. A recognized `input_scaling` key
        overrides the bound `self.input_scaling` for this call only (the
        shared per-call contract — see
        `resdag.init.input_feedback.InputFeedbackInitializer`);
        other keys are ignored.

    Returns
    -------
    torch.Tensor
        Initialized weight tensor with binary values
    """
    out_features, in_features = _resolve_shape(weight)
    device = weight.device
    dtype = weight.dtype

    generator = self._torch_generator_for(device)

    # Draw bits {0, 1} on the target device, then map to {-1, +1}.
    bits = torch.randint(0, 2, (out_features, in_features), generator=generator, device=device)
    values = (bits.to(dtype) * 2.0) - 1.0

    # Apply the shared uniform scaling contract as the documented final
    # transform (torch-native, staying on-device). Forward ``**kwargs`` so a
    # per-call ``input_scaling`` override wins over the bound value.
    values = self._apply_scaling(values, **kwargs)

    with torch.no_grad():
        weight.copy_(values)

    return weight

RandomInputInitializer

RandomInputInitializer(input_scaling: float | None = None, seed: SeedLike = None)

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 resdag.init.input_feedback.InputFeedbackInitializer). None (the default) applies no scaling, leaving entries in [-1, 1]; a float s multiplies every entry by s, so max|W| scales linearly with s (input_scaling=0.5 halves it). Controls the strength of input signals entering the reservoir. Typical values: 0.1-5.0.

TYPE: float DEFAULT: None

seed

Reproducibility seed for the uniform draw. Accepts a plain int, a torch.Generator (whose initial_seed() is used, so a generator and the equivalent int agree), or None (defer to torch's global RNG). The draw is device-native: it happens directly on the target weight's device via a torch generator, so the same seed is reproducible per device (CPU and CUDA each reproduce, though their RNG streams differ from each other). Ensures the same weight matrix is generated for the same seed, shape, and device.

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

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
def __init__(
    self,
    input_scaling: float | None = None,
    seed: SeedLike = None,
) -> None:
    """Initialize the RandomInputInitializer."""
    super().__init__(input_scaling=input_scaling, seed=seed)

initialize

initialize(weight: Tensor, **kwargs: Any) -> Tensor

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

**kwargs

Per-call keyword overrides. A recognized input_scaling key overrides the bound self.input_scaling for this call only (the shared per-call contract — see resdag.init.input_feedback.InputFeedbackInitializer); other keys are ignored.

TYPE: Any DEFAULT: {}

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
def initialize(self, weight: torch.Tensor, **kwargs: Any) -> torch.Tensor:
    """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`).

    Parameters
    ----------
    weight : torch.Tensor
        Weight tensor of shape (out_features, in_features)
    **kwargs
        Per-call keyword overrides. A recognized `input_scaling` key
        overrides the bound `self.input_scaling` for this call only (the
        shared per-call contract — see
        `resdag.init.input_feedback.InputFeedbackInitializer`);
        other keys are ignored.

    Returns
    -------
    torch.Tensor
        Initialized weight tensor
    """
    out_features, in_features = _resolve_shape(weight)
    device = weight.device
    dtype = weight.dtype

    generator = self._torch_generator_for(device)

    # Draw uniform values in [-1, 1] directly on the target device.
    values = torch.empty(out_features, in_features, device=device, dtype=dtype)
    values.uniform_(-1.0, 1.0, generator=generator)

    # Apply the shared uniform scaling contract as the documented final
    # transform (torch-native, staying on-device). Forward ``**kwargs`` so a
    # per-call ``input_scaling`` override wins over the bound value.
    values = self._apply_scaling(values, **kwargs)

    with torch.no_grad():
        weight.copy_(values)

    return weight

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

window

If int >= 1: number of core nodes per channel window. If float in (0, 1]: fraction of C per channel window (rounded >= 1).

TYPE: int or float

taper

Weight profile within a channel's window centered on its center index.

TYPE: (flat, triangle, cosine) DEFAULT: "flat"

signed

Sign policy for weights.

TYPE: (allpos, alt_ring, alt_inputs) DEFAULT: "allpos"

input_scaling

Per-channel L2-norm after taper/sign are applied. Defaults to 1.0 when neither input_scaling nor the deprecated gain is given.

TYPE: float DEFAULT: None

gain

Deprecated alias for input_scaling (same meaning). Emits a DeprecationWarning; passing both input_scaling and gain raises.

TYPE: float DEFAULT: None

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
def __init__(
    self,
    c: float,
    window: int | float,
    taper: str = "flat",
    signed: str = "allpos",
    input_scaling: float | None = None,
    gain: float | None = None,
) -> None:
    """Initialize the RingWindowInputInitializer."""
    if not (0 < c <= 1):
        raise ValueError("c must be in (0,1].")
    self.c = float(c)

    self.window: int | float
    if isinstance(window, int):
        if window < 1:
            raise ValueError("window int must be >= 1.")
        self.window = window
        self.window_is_frac = False
    elif isinstance(window, float):
        if not (0 < window <= 1):
            raise ValueError("window float must be in (0,1].")
        self.window = float(window)
        self.window_is_frac = True
    else:
        raise TypeError("window must be int or float.")

    if taper not in {"flat", "triangle", "cosine"}:
        raise ValueError("taper must be 'flat', 'triangle', or 'cosine'.")
    if signed not in {"allpos", "alt_ring", "alt_inputs"}:
        raise ValueError("signed must be 'allpos', 'alt_ring', or 'alt_inputs'.")

    resolved = _resolve_scaling_alias(input_scaling, gain, default=1.0)
    if resolved is None or not (np.isfinite(resolved) and resolved > 0):
        raise ValueError("input_scaling must be a positive finite float.")
    super().__init__(input_scaling=resolved)

    self.taper = taper
    self.signed = signed

gain property

gain: float | None

Deprecated alias for input_scaling.

initialize

initialize(weight: Tensor, **kwargs: Any) -> Tensor

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

**kwargs

Per-call keyword overrides. A recognized input_scaling key overrides the bound self.input_scaling (the per-channel L2-norm target) for this call only (the shared per-call contract — see resdag.init.input_feedback.InputFeedbackInitializer); other keys are ignored. The override must be a positive finite float (None is not accepted for this structured initializer).

TYPE: Any DEFAULT: {}

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
def initialize(self, weight: torch.Tensor, **kwargs: Any) -> torch.Tensor:
    """Initialize weight tensor with ring window pattern.

    Parameters
    ----------
    weight : torch.Tensor
        Weight tensor of shape (out_features, in_features)
        out_features = reservoir_size (n)
        in_features = num_inputs (m)
    **kwargs
        Per-call keyword overrides. A recognized `input_scaling` key
        overrides the bound `self.input_scaling` (the per-channel L2-norm
        target) for this call only (the shared per-call contract — see
        `resdag.init.input_feedback.InputFeedbackInitializer`);
        other keys are ignored. The override must be a positive finite float
        (`None` is not accepted for this structured initializer).

    Returns
    -------
    torch.Tensor
        Initialized weight tensor
    """
    n, m = _resolve_shape(weight)
    device = weight.device
    dtype = weight.dtype
    compute_dtype = _numpy_compute_dtype(dtype)

    if m <= 0 or n <= 0:
        raise ValueError("m and n must be positive.")

    C = max(1, int(round(self.c * n)))  # core size
    W = self._window_size(C)

    # ``input_scaling`` is the per-channel L2 norm target. Resolve the
    # effective value from the per-call ``**kwargs`` (a recognized
    # ``input_scaling`` key wins) with the bound value as fallback, so a
    # per-call override is honored. The bound value is never None (the
    # constructor resolves the alias and defaults it to 1.0); a per-call
    # override must likewise be a positive finite float for this structured
    # initializer.
    scaling_resolved = self._resolve_input_scaling(kwargs)
    if scaling_resolved is None or not (np.isfinite(scaling_resolved) and scaling_resolved > 0):
        raise ValueError("input_scaling must be a positive finite float.")
    scaling = float(scaling_resolved)

    # Build at the target precision so the float64 taper/norm computation is
    # not truncated to float32 before reaching a float64 weight.
    values = np.zeros((n, m), dtype=compute_dtype)
    base = self._taper_vector(W, self.taper).astype(compute_dtype)

    def window_indices(center: int) -> np.ndarray:
        start = center - (W // 2)
        return (np.arange(start, start + W) % C).astype(int)

    for k in range(m):
        start = int(np.floor(k * C / m)) % C
        center = (start + (W - 1) // 2) % C

        cols_core = window_indices(center)
        row_vals = base.copy()

        signs: float | np.ndarray
        if self.signed == "allpos":
            signs = 1.0
        elif self.signed == "alt_ring":
            signs = (1.0 - 2.0 * (cols_core % 2)).astype(compute_dtype)
        else:  # "alt_inputs"
            signs = 1.0 if (k % 2 == 0) else -1.0

        row_vals = row_vals * signs
        norm = float(np.linalg.norm(row_vals))
        scaled = row_vals if norm == 0.0 else (scaling / norm) * row_vals

        values[cols_core, k] = scaled  # Only core; rest stay zero

    # Convert to tensor and copy to weight
    weight_data = torch.from_numpy(values).to(device=device, dtype=dtype)

    with torch.no_grad():
        weight.copy_(weight_data)

    return weight

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 -1.0. Must be strictly less than high.

TYPE: float DEFAULT: -1.0

high

Exclusive upper bound of the uniform draw. Defaults to 1.0.

TYPE: float DEFAULT: 1.0

connectivity

Density knob from the shared scaling contract (see resdag.init.input_feedback.InputFeedbackInitializer): the fraction of nonzero entries kept per column (input channel), in (0, 1]. None (the default) leaves the dense matrix untouched; connectivity=0.1 keeps ~10% of each column's entries (at least one), zeroing the rest. The kept fraction is statistically exact: round(connectivity * reservoir_size) entries per column.

TYPE: float DEFAULT: None

input_scaling

Uniform magnitude knob from the shared scaling contract. None (the default) applies no scaling; a float s multiplies every entry by s, so max|W| scales linearly with s (input_scaling=0.5 halves it). Applied after the [low, high] draw, so it rescales the bounds rather than replacing them.

TYPE: float DEFAULT: None

seed

Reproducibility seed for the uniform draw and the connectivity mask. Accepts a plain int, a torch.Generator (whose initial_seed() is used, so a generator and the equivalent int agree), or None (defer to torch's global RNG). The value draw is device-native: it happens directly on the target weight's device via a torch generator, so the same seed is reproducible per device (CPU and CUDA each reproduce, though their RNG streams differ from each other).

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

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
def __init__(
    self,
    low: float = -1.0,
    high: float = 1.0,
    connectivity: float | None = None,
    input_scaling: float | None = None,
    seed: SeedLike = None,
) -> None:
    """Initialize the UniformInputInitializer."""
    super().__init__(
        input_scaling=input_scaling,
        connectivity=connectivity,
        seed=seed,
    )
    low = float(low)
    high = float(high)
    if not low < high:
        raise ValueError(
            f"low must be strictly less than high; got low={low!r}, high={high!r}."
        )
    self.low = low
    self.high = high

initialize

initialize(weight: Tensor, **kwargs: Any) -> Tensor

Initialize weight with Uniform(low, high) entries.

PARAMETER DESCRIPTION
weight

Weight tensor of shape (out_features, in_features). Modified in-place.

TYPE: Tensor

**kwargs

Per-call keyword overrides. Recognized input_scaling and connectivity keys override the bound attributes for this call only (the shared per-call contract — see resdag.init.input_feedback.InputFeedbackInitializer); other keys are ignored.

TYPE: Any DEFAULT: {}

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
def initialize(self, weight: torch.Tensor, **kwargs: Any) -> torch.Tensor:
    """Initialize `weight` with `Uniform(low, high)` entries.

    Parameters
    ----------
    weight : torch.Tensor
        Weight tensor of shape `(out_features, in_features)`. Modified
        in-place.
    **kwargs
        Per-call keyword overrides. Recognized `input_scaling` and
        `connectivity` keys override the bound attributes for this call
        only (the shared per-call contract — see
        `resdag.init.input_feedback.InputFeedbackInitializer`);
        other keys are ignored.

    Returns
    -------
    torch.Tensor
        The initialized weight tensor (same object, modified in-place).
    """
    out_features, in_features = _resolve_shape(weight)
    device = weight.device
    dtype = weight.dtype

    generator = self._torch_generator_for(device)

    # Draw uniform values in [low, high) directly on the target device.
    values = torch.empty(out_features, in_features, device=device, dtype=dtype)
    values.uniform_(self.low, self.high, generator=generator)

    # Apply the shared connectivity then scaling contract, in that order
    # (zeroing then scaling is identical either way; this matches the base
    # class's documented composition ``_apply_scaling(_apply_connectivity)``).
    # Forward ``**kwargs`` so per-call ``connectivity`` / ``input_scaling``
    # overrides win over the bound values.
    values = self._apply_connectivity(values, **kwargs)
    values = self._apply_scaling(values, **kwargs)

    with torch.no_grad():
        weight.copy_(values)

    return weight

WeightedInputInitializer

WeightedInputInitializer(input_scaling: float | None = 0.1, seed: int | None = None)

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 [-input_scaling, input_scaling] (RC.jl scaling). This is the shared scaling-contract knob, so max|W| scales linearly with it.

TYPE: float DEFAULT: 0.1

seed

Reproducibility seed for the uniform block draws. None draws fresh each call.

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

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
def __init__(
    self,
    input_scaling: float | None = 0.1,
    seed: int | None = None,
) -> None:
    """Initialize the WeightedInputInitializer."""
    super().__init__(input_scaling=input_scaling, seed=seed)

initialize

initialize(weight: Tensor, **kwargs: Any) -> Tensor

Fill a block-diagonal weight with uniform block values.

PARAMETER DESCRIPTION
weight

Weight tensor of shape (out_features, in_features).

TYPE: Tensor

**kwargs

Per-call keyword overrides. A recognized input_scaling key overrides the bound self.input_scaling for this call only (the shared per-call contract); other keys are ignored.

TYPE: Any DEFAULT: {}

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
def initialize(self, weight: torch.Tensor, **kwargs: Any) -> torch.Tensor:
    """Fill a block-diagonal weight with uniform block values.

    Parameters
    ----------
    weight : torch.Tensor
        Weight tensor of shape `(out_features, in_features)`.
    **kwargs
        Per-call keyword overrides. A recognized `input_scaling` key
        overrides the bound `self.input_scaling` for this call only (the
        shared per-call contract); other keys are ignored.

    Returns
    -------
    torch.Tensor
        The initialized weight tensor (modified in-place).
    """
    out_features, in_features = _resolve_shape(weight)
    device = weight.device
    dtype = weight.dtype
    compute_dtype = _numpy_compute_dtype(dtype)

    rng = create_rng(coerce_seed_to_int(self.seed))
    q = _block_size(out_features, in_features)

    # Natural range is [-1, 1]; the shared scaling contract multiplies by
    # ``input_scaling`` to land the RC.jl ``[-scaling, scaling]`` block range.
    values = np.zeros((out_features, in_features), dtype=compute_dtype)
    for idx in range(in_features):
        block = rng.uniform(-1.0, 1.0, size=(q,)).astype(compute_dtype)
        values[idx * q : (idx + 1) * q, idx] = block

    # Forward ``**kwargs`` so a per-call ``input_scaling`` override wins.
    values = self._apply_scaling(values, **kwargs)

    weight_data = torch.from_numpy(values).to(device=device, dtype=dtype)
    with torch.no_grad():
        weight.copy_(weight_data)
    return weight

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 weight).

TYPE: float DEFAULT: 0.1

sign_rule

Sign-assignment rule (RC.jl sampling_type without _sample!). RC.jl's weighted_minimal defaults to :no_sample (all positive).

TYPE: (none, bernoulli, irrational, regular) DEFAULT: "none"

positive_prob

Probability an entry stays positive under sign_rule="bernoulli".

TYPE: float DEFAULT: 0.5

start

First pi-digit offset under sign_rule="irrational".

TYPE: int DEFAULT: 1

strides

Stride under sign_rule="regular".

TYPE: int DEFAULT: 2

input_scaling

Uniform magnitude knob from the shared scaling contract. None leaves nonzero entries at magnitude weight; a float s multiplies every entry by s (applied on top of weight).

TYPE: float DEFAULT: None

seed

Reproducibility seed for the "bernoulli" sign draw; ignored by the deterministic rules.

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

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
def __init__(
    self,
    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,
) -> None:
    """Initialize the WeightedMinimalInitializer."""
    super().__init__(input_scaling=input_scaling, seed=seed)
    self.weight = float(weight)
    self.sign_rule = sign_rule
    self.positive_prob = float(positive_prob)
    self.start = int(start)
    self.strides = int(strides)

initialize

initialize(weight: Tensor, **kwargs: Any) -> Tensor

Fill a block-diagonal weight with constant-magnitude signed entries.

PARAMETER DESCRIPTION
weight

Weight tensor of shape (out_features, in_features).

TYPE: Tensor

**kwargs

Per-call keyword overrides. A recognized input_scaling key overrides the bound self.input_scaling for this call only (the shared per-call contract); other keys are ignored.

TYPE: Any DEFAULT: {}

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
def initialize(self, weight: torch.Tensor, **kwargs: Any) -> torch.Tensor:
    """Fill a block-diagonal weight with constant-magnitude signed entries.

    Parameters
    ----------
    weight : torch.Tensor
        Weight tensor of shape `(out_features, in_features)`.
    **kwargs
        Per-call keyword overrides. A recognized `input_scaling` key
        overrides the bound `self.input_scaling` for this call only (the
        shared per-call contract); other keys are ignored.

    Returns
    -------
    torch.Tensor
        The initialized weight tensor (modified in-place).
    """
    out_features, in_features = _resolve_shape(weight)
    device = weight.device
    dtype = weight.dtype
    compute_dtype = _numpy_compute_dtype(dtype)

    rng = create_rng(coerce_seed_to_int(self.seed))
    q = _block_size(out_features, in_features)

    # Build the constant-magnitude block matrix (off-block entries stay 0).
    values = np.zeros((out_features, in_features), dtype=compute_dtype)
    for idx in range(in_features):
        values[idx * q : (idx + 1) * q, idx] = self.weight

    # RC.jl runs the sampler over the whole matrix after building the blocks.
    signs = build_sign_matrix(
        out_features,
        in_features,
        self.sign_rule,
        positive_prob=self.positive_prob,
        start=self.start,
        strides=self.strides,
        rng=rng,
    )
    values = values * signs.astype(compute_dtype)

    # Forward ``**kwargs`` so a per-call ``input_scaling`` override wins.
    values = self._apply_scaling(values, **kwargs)

    weight_data = torch.from_numpy(values).to(device=device, dtype=dtype)
    with torch.no_grad():
        weight.copy_(weight_data)
    return weight

ZeroInitializer

ZeroInitializer()

Bases: InputFeedbackInitializer

Initializer that sets all weights to zero.

Source code in src/resdag/init/input_feedback/zero.py
13
14
15
def __init__(self) -> None:
    """Initialize the ZeroInitializer."""
    super().__init__()

initialize

initialize(weight: Tensor, **kwargs: Any) -> Tensor

Initialize weight tensor with zero values.

Source code in src/resdag/init/input_feedback/zero.py
17
18
19
20
21
def initialize(self, weight: torch.Tensor, **kwargs: Any) -> torch.Tensor:
    """Initialize weight tensor with zero values."""
    with torch.no_grad():
        weight.zero_()
    return weight

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

**override_kwargs

Keyword arguments to override default initializer parameters

TYPE: Any DEFAULT: {}

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
def get_input_feedback(
    name: str,
    **override_kwargs: Any,
) -> InputFeedbackInitializer:
    """Get a pre-configured input/feedback initializer by name.

    Parameters
    ----------
    name : str
        Name of the initializer (e.g., "random", "binary_balanced")
    **override_kwargs
        Keyword arguments to override default initializer parameters

    Returns
    -------
    InputFeedbackInitializer
        Initializer instance

    Raises
    ------
    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)
    """
    if name not in _INPUT_FEEDBACK_REGISTRY:
        available = ", ".join(_INPUT_FEEDBACK_REGISTRY.keys())
        raise ValueError(f"Unknown initializer '{name}'. Available initializers: {available}")

    entry, default_kwargs = _INPUT_FEEDBACK_REGISTRY[name]

    # Merge default kwargs with overrides
    kwargs = {**default_kwargs, **override_kwargs}

    if inspect.isclass(entry) and issubclass(entry, InputFeedbackInitializer):
        return entry(**kwargs)
    return FunctionInitializer(entry, **kwargs)

register_input_feedback

register_input_feedback(
    name: str, **default_kwargs: Any
) -> Callable[[Callable], Callable]

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

**default_kwargs

Default keyword arguments for the initializer constructor (classes) or for the function call (plain functions)

TYPE: Any DEFAULT: {}

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 InputFeedbackInitializer and implement initialize(weight, **kwargs).
  • Functions follow the FunctionInitializer conventions: fn(rows, cols, **kwargs) -> matrix or in-place fn(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
def register_input_feedback(
    name: str,
    **default_kwargs: Any,
) -> Callable[[Callable], Callable]:
    """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.

    Parameters
    ----------
    name : str
        Name for the initializer (must be unique)
    **default_kwargs
        Default keyword arguments for the initializer constructor (classes)
        or for the function call (plain functions)

    Returns
    -------
    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 `InputFeedbackInitializer` and implement
      `initialize(weight, **kwargs)`.
    - Functions follow the `FunctionInitializer` conventions:
      `fn(rows, cols, **kwargs) -> matrix` or in-place `fn(tensor, **kwargs)`.
    - Registered initializers can be accessed via `get_input_feedback(name)`.
    """

    def decorator(obj: Callable) -> Callable:
        if name in _INPUT_FEEDBACK_REGISTRY:
            raise ValueError(f"Input/feedback initializer '{name}' is already registered")
        _INPUT_FEEDBACK_REGISTRY[name] = (obj, default_kwargs)
        return obj

    return decorator

show_input_initializers

show_input_initializers(name: str | None = None) -> list[str] | None

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

RETURNS DESCRIPTION
list of str or None

When name is None, returns the sorted list of registered initializer names (in addition to printing them). When name is provided, returns None after printing the parameter table.

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
def show_input_initializers(name: str | None = None) -> list[str] | None:
    """Show available input/feedback initializers or details for a specific one.

    Parameters
    ----------
    name : str, optional
        Name of initializer to inspect. If None, prints all initializers
        *and* returns them as a list.

    Returns
    -------
    list of str or None
        When `name is None`, returns the sorted list of registered
        initializer names (in addition to printing them).  When `name`
        is provided, returns `None` after printing the parameter table.

    Raises
    ------
    ValueError
        If the specified initializer name is not registered.

    Examples
    --------
    >>> show_input_initializers()
    ['binary_balanced', 'chebyshev', 'chessboard', ...]
    """
    if name is None:
        names = sorted(_INPUT_FEEDBACK_REGISTRY)
        print("\nAvailable input/feedback initializers:\n")
        for n in names:
            print(f"  - {n}")
        print(f"\nTotal: {len(names)}\n")
        return names

    if name not in _INPUT_FEEDBACK_REGISTRY:
        available = "\n".join(sorted(_INPUT_FEEDBACK_REGISTRY.keys()))
        raise ValueError(f"Unknown initializer '{name}'.\nAvailable:\n{available}")

    entry, default_kwargs = _INPUT_FEEDBACK_REGISTRY[name]
    is_class = inspect.isclass(entry)
    sig = inspect.signature(entry.__init__) if is_class else inspect.signature(entry)

    print(f"\nInitializer: {name} ({'class' if is_class else 'function'})\n")
    print("Parameters:\n")

    # Skip non-hyperparameter params: self (classes) and the matrix
    # dimensions / target tensor (functions).
    skip = {"self"} if is_class else {"rows", "cols", "tensor", "weight"}
    for param_name, param in sig.parameters.items():
        if param_name in skip:
            continue

        # Type extraction
        annotation = param.annotation
        type_str = (
            "Any"
            if annotation is inspect.Parameter.empty
            else annotation if isinstance(annotation, str) else inspect.formatannotation(annotation)
        )

        # Default resolution
        if param_name in default_kwargs:
            default = default_kwargs[param_name]
        elif param.default is not inspect.Parameter.empty:
            default = param.default
        else:
            default = default_kwargs.get(param_name, "<required>")

        print(f"  - {param_name}")
        print(f"      type:    {type_str}")
        print(f"      default: {default}\n")

    return None

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 ("orthogonal").

antisymmetric_matrix

Random antisymmetric (skew-symmetric) matrix A - A^T with purely imaginary eigenvalues ("antisymmetric").

fast_spectral_initialization

Recurrent matrix built at a target spectral radius analytically, with no eigendecomposition ("fast_spectral_initialization").

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 ("delay_line", "delay_line_backward", "simple_cycle", "cycle_jumps", "self_loop_cycle").

toeplitz, band, block_diagonal

Structured reservoirs — a Toeplitz (constant-per-diagonal) matrix, a banded matrix, and a block-diagonal matrix ("toeplitz", "band", "block_diagonal").

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

scaling

Multiplicative gain applied to the antisymmetric part. Only the raw scale — the antisymmetry is independent of it.

TYPE: float DEFAULT: 1.0

seed

Seed for the Gaussian draw. None uses the global torch RNG (so the result is reproducible under torch.manual_seed).

TYPE: int DEFAULT: None

dtype

Real floating-point output and random-draw dtype.

TYPE: dtype DEFAULT: torch.float32

device

Allocation and random-draw device (CPU by default).

TYPE: device or str DEFAULT: None

RETURNS DESCRIPTION
Tensor

Dense (n, n) antisymmetric matrix on the requested dtype/device.

RAISES DESCRIPTION
ValueError

If n is not a positive integer.

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
@register_matrix_topology("antisymmetric", scaling=1.0)
def antisymmetric_matrix(
    n: int,
    scaling: float = 1.0,
    seed: int | None = None,
    *,
    dtype: torch.dtype = torch.float32,
    device: torch.device | str | None = None,
) -> torch.Tensor:
    r"""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.

    Parameters
    ----------
    n : int
        Matrix size (number of reservoir units).
    scaling : float, default=1.0
        Multiplicative gain applied to the antisymmetric part.  Only the raw
        scale — the antisymmetry is independent of it.
    seed : int, optional
        Seed for the Gaussian draw.  `None` uses the global torch RNG (so the
        result is reproducible under `torch.manual_seed`).
    dtype : torch.dtype, default=torch.float32
        Real floating-point output and random-draw dtype.
    device : torch.device or str, optional
        Allocation and random-draw device (CPU by default).

    Returns
    -------
    torch.Tensor
        Dense `(n, n)` antisymmetric matrix on the requested dtype/device.

    Raises
    ------
    ValueError
        If `n` is not a positive integer.

    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
    ... )
    """
    target = matrix_device(n, dtype, device)
    scaling = finite_scalar(scaling, "scaling")
    generator = seeded_generator(seed, target)
    a = torch.randn(n, n, generator=generator, dtype=dtype, device=target)
    return scaling * (a - a.t())

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

weight

Constant assigned to every in-band entry, including the main diagonal.

TYPE: float DEFAULT: 0.1

bandwidth

Half-bandwidth, satisfying 0 <= bandwidth < n. Two populates the main diagonal and two diagonals on either side.

TYPE: int DEFAULT: 1

dtype

Real floating-point output dtype.

TYPE: dtype DEFAULT: torch.float32

device

Allocation device (CPU by default).

TYPE: device or str DEFAULT: None

RETURNS DESCRIPTION
Tensor

Dense symmetric (n, n) matrix with constant in-band weights.

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
@register_matrix_topology("band", weight=0.1, bandwidth=1)
def band(
    n: int,
    weight: float = 0.1,
    bandwidth: int = 1,
    *,
    dtype: torch.dtype = torch.float32,
    device: torch.device | str | None = None,
) -> torch.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.

    Parameters
    ----------
    n : int
        Number of reservoir units, a positive integer.
    weight : float, default=0.1
        Constant assigned to every in-band entry, including the main diagonal.
    bandwidth : int, default=1
        Half-bandwidth, satisfying `0 <= bandwidth < n`. Two populates the
        main diagonal and two diagonals on either side.
    dtype : torch.dtype, default=torch.float32
        Real floating-point output dtype.
    device : torch.device or str, optional
        Allocation device (CPU by default).

    Returns
    -------
    torch.Tensor
        Dense symmetric `(n, n)` matrix with constant in-band weights.

    Raises
    ------
    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}),
    ... )
    """
    target = matrix_device(n, dtype, device)
    if not 0 <= bandwidth < n:
        raise ValueError(f"bandwidth must satisfy 0 <= bandwidth < n={n}, got {bandwidth}")
    rows = torch.arange(n, device=target).view(n, 1)
    cols = torch.arange(n, device=target).view(1, n)
    in_band = (cols - rows).abs() <= bandwidth
    return torch.where(
        in_band,
        torch.full((n, n), float(weight), dtype=dtype, device=target),
        torch.zeros((n, n), dtype=dtype, device=target),
    )

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

weight

Constant filling every element of each complete block.

TYPE: float DEFAULT: 1.0

block_size

Square block side length, satisfying 1 <= block_size <= n. One gives a scaled identity. Any trailing incomplete block is left zero.

TYPE: int DEFAULT: 1

dtype

Real floating-point output dtype.

TYPE: dtype DEFAULT: torch.float32

device

Allocation device (CPU by default).

TYPE: device or str DEFAULT: None

RETURNS DESCRIPTION
Tensor

Dense (n, n) tensor with floor(n / block_size) constant blocks. When weight is nonzero its rank is the number of complete blocks.

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
@register_matrix_topology("block_diagonal", weight=1.0, block_size=1)
def block_diagonal(
    n: int,
    weight: float = 1.0,
    block_size: int = 1,
    *,
    dtype: torch.dtype = torch.float32,
    device: torch.device | str | None = None,
) -> torch.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.

    Parameters
    ----------
    n : int
        Number of reservoir units, a positive integer.
    weight : float, default=1.0
        Constant filling every element of each complete block.
    block_size : int, default=1
        Square block side length, satisfying `1 <= block_size <= n`. One
        gives a scaled identity. Any trailing incomplete block is left zero.
    dtype : torch.dtype, default=torch.float32
        Real floating-point output dtype.
    device : torch.device or str, optional
        Allocation device (CPU by default).

    Returns
    -------
    torch.Tensor
        Dense `(n, n)` tensor with `floor(n / block_size)` constant blocks.
        When weight is nonzero its rank is the number of complete blocks.

    Raises
    ------
    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}),
    ... )
    """
    target = matrix_device(n, dtype, device)
    if not 1 <= block_size <= n:
        raise ValueError(f"block_size must satisfy 1 <= block_size <= n={n}, got {block_size}")
    matrix = torch.zeros(n, n, dtype=dtype, device=target)
    for start in range(0, n - block_size + 1, block_size):
        matrix[start : start + block_size, start : start + block_size] = float(weight)
    return matrix

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

cycle_weight

Constant weight of the unidirectional cycle edges.

TYPE: float DEFAULT: 0.1

jump_weight

Constant weight of both directions of each jump edge.

TYPE: float DEFAULT: 0.1

jump_size

Distance between successive jump-chain nodes. Must satisfy 1 <= jump_size < n; divisibility determines the closing jump.

TYPE: int DEFAULT: 3

dtype

Real floating-point output dtype.

TYPE: dtype DEFAULT: torch.float32

device

Allocation device (CPU by default).

TYPE: device or str DEFAULT: None

RETURNS DESCRIPTION
Tensor

Dense (n, n) cycle with symmetric jump connections. For example, n=7, jump_size=3 adds 0 <-> 3 and 3 <-> 6 only.

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
@register_matrix_topology("cycle_jumps", cycle_weight=0.1, jump_weight=0.1, jump_size=3)
def cycle_jumps(
    n: int,
    cycle_weight: float = 0.1,
    jump_weight: float = 0.1,
    jump_size: int = 3,
    *,
    dtype: torch.dtype = torch.float32,
    device: torch.device | str | None = None,
) -> torch.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`.

    Parameters
    ----------
    n : int
        Number of reservoir units, a positive integer greater than jump_size.
    cycle_weight : float, default=0.1
        Constant weight of the unidirectional cycle edges.
    jump_weight : float, default=0.1
        Constant weight of both directions of each jump edge.
    jump_size : int, default=3
        Distance between successive jump-chain nodes. Must satisfy
        `1 <= jump_size < n`; divisibility determines the closing jump.
    dtype : torch.dtype, default=torch.float32
        Real floating-point output dtype.
    device : torch.device or str, optional
        Allocation device (CPU by default).

    Returns
    -------
    torch.Tensor
        Dense `(n, n)` cycle with symmetric jump connections. For example,
        `n=7, jump_size=3` adds `0 <-> 3` and `3 <-> 6` only.

    Raises
    ------
    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.
    """
    target = matrix_device(n, dtype, device)
    if not 1 <= jump_size < n:
        raise ValueError(f"jump_size must satisfy 1 <= jump_size < n={n}, got {jump_size}")
    matrix = _build_simple_cycle(n, float(cycle_weight), dtype=dtype, device=target)
    nodes = list(range(0, n, jump_size))
    for left, right in zip(nodes, nodes[1:]):
        matrix[left, right] = float(jump_weight)
        matrix[right, left] = float(jump_weight)
    if n % jump_size == 0:
        matrix[nodes[-1], 0] = float(jump_weight)
        matrix[0, nodes[-1]] = float(jump_weight)
    return matrix

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

TYPE: int

weight

Constant weight of every forward connection. It controls how much past activity remains after each shift along the delay line.

TYPE: float DEFAULT: 0.1

shift

Subdiagonal offset. One connects each unit to its next neighbour; larger offsets skip units. Must satisfy 1 <= shift < n.

TYPE: int DEFAULT: 1

dtype

Real floating-point output dtype; float64 avoids a float32 conversion.

TYPE: dtype DEFAULT: torch.float32

device

Allocation device, CPU by default. CUDA/MPS allocation is direct.

TYPE: device or str DEFAULT: None

RETURNS DESCRIPTION
Tensor

Dense (n, n) tensor with the chosen subdiagonal and zeros elsewhere.

RAISES DESCRIPTION
ValueError

If n is invalid, shift is outside its range, or dtype is not real floating-point.

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
@register_matrix_topology("delay_line", weight=0.1, shift=1)
def delay_line(
    n: int,
    weight: float = 0.1,
    shift: int = 1,
    *,
    dtype: torch.dtype = torch.float32,
    device: torch.device | str | None = None,
) -> torch.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.

    Parameters
    ----------
    n : int
        Number of reservoir units; a positive integer greater than `shift`.
    weight : float, default=0.1
        Constant weight of every forward connection. It controls how much
        past activity remains after each shift along the delay line.
    shift : int, default=1
        Subdiagonal offset. One connects each unit to its next neighbour;
        larger offsets skip units. Must satisfy `1 <= shift < n`.
    dtype : torch.dtype, default=torch.float32
        Real floating-point output dtype; float64 avoids a float32 conversion.
    device : torch.device or str, optional
        Allocation device, CPU by default. CUDA/MPS allocation is direct.

    Returns
    -------
    torch.Tensor
        Dense `(n, n)` tensor with the chosen subdiagonal and zeros elsewhere.

    Raises
    ------
    ValueError
        If `n` is invalid, `shift` is outside its range, or dtype is not
        real floating-point.

    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.
    """
    target = matrix_device(n, dtype, device)
    if not 1 <= shift < n:
        raise ValueError(f"shift must satisfy 1 <= shift < n={n}, got {shift}")
    matrix = torch.zeros(n, n, dtype=dtype, device=target)
    idx = torch.arange(n - shift, device=target)
    matrix[idx + shift, idx] = float(weight)
    return matrix

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

weight

Weight on the forward subdiagonal.

TYPE: float DEFAULT: 0.1

backward_weight

Weight on the reverse superdiagonal. A negative weight changes the sign of backward feedback independently of the forward path.

TYPE: float DEFAULT: 0.1

shift

Forward subdiagonal offset, satisfying 1 <= shift < n.

TYPE: int DEFAULT: 1

backward_shift

Backward superdiagonal offset, satisfying 1 <= backward_shift < n.

TYPE: int DEFAULT: 1

dtype

Real floating-point output dtype.

TYPE: dtype DEFAULT: torch.float32

device

Allocation device (CPU by default).

TYPE: device or str DEFAULT: None

RETURNS DESCRIPTION
Tensor

Dense (n, n) tensor with one subdiagonal and one superdiagonal.

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
@register_matrix_topology(
    "delay_line_backward", weight=0.1, backward_weight=0.1, shift=1, backward_shift=1
)
def delay_line_backward(
    n: int,
    weight: float = 0.1,
    backward_weight: float = 0.1,
    shift: int = 1,
    backward_shift: int = 1,
    *,
    dtype: torch.dtype = torch.float32,
    device: torch.device | str | None = None,
) -> torch.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.

    Parameters
    ----------
    n : int
        Number of reservoir units, a positive integer.
    weight : float, default=0.1
        Weight on the forward subdiagonal.
    backward_weight : float, default=0.1
        Weight on the reverse superdiagonal. A negative weight changes the
        sign of backward feedback independently of the forward path.
    shift : int, default=1
        Forward subdiagonal offset, satisfying `1 <= shift < n`.
    backward_shift : int, default=1
        Backward superdiagonal offset, satisfying `1 <= backward_shift < n`.
    dtype : torch.dtype, default=torch.float32
        Real floating-point output dtype.
    device : torch.device or str, optional
        Allocation device (CPU by default).

    Returns
    -------
    torch.Tensor
        Dense `(n, n)` tensor with one subdiagonal and one superdiagonal.

    Raises
    ------
    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.
    """
    target = matrix_device(n, dtype, device)
    if not 1 <= shift < n:
        raise ValueError(f"shift must satisfy 1 <= shift < n={n}, got {shift}")
    if not 1 <= backward_shift < n:
        raise ValueError(
            f"backward_shift must satisfy 1 <= backward_shift < n={n}, got {backward_shift}"
        )
    matrix = torch.zeros(n, n, dtype=dtype, device=target)
    fwd = torch.arange(n - shift, device=target)
    matrix[fwd + shift, fwd] = float(weight)
    bwd = torch.arange(n - backward_shift, device=target)
    matrix[bwd, bwd + backward_shift] = float(backward_weight)
    return matrix

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

spectral_radius

Target spectral radius \(\rho\). For finite n the realized radius fluctuates around this value (the circular law is asymptotic); the relative error shrinks as n grows.

TYPE: float DEFAULT: 0.9

seed

Seed for the uniform draw. None uses the global torch RNG, so the result is reproducible under torch.manual_seed.

TYPE: int DEFAULT: None

dtype

Real floating-point output and random-draw dtype.

TYPE: dtype DEFAULT: torch.float32

device

Allocation and random-draw device (CPU by default).

TYPE: device or str DEFAULT: None

RETURNS DESCRIPTION
Tensor

Dense (n, n) recurrent matrix on the requested dtype/device, with spectral radius approximately equal to spectral_radius.

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
@register_matrix_topology("fast_spectral_initialization", spectral_radius=0.9)
def fast_spectral_initialization(
    n: int,
    spectral_radius: float = 0.9,
    seed: int | None = None,
    *,
    dtype: torch.dtype = torch.float32,
    device: torch.device | str | None = None,
) -> torch.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.

    Parameters
    ----------
    n : int
        Matrix size (number of reservoir units).
    spectral_radius : float, default=0.9
        Target spectral radius $\\rho$.  For finite `n` the realized
        radius fluctuates around this value (the circular law is asymptotic);
        the relative error shrinks as `n` grows.
    seed : int, optional
        Seed for the uniform draw.  `None` uses the global torch RNG, so the
        result is reproducible under `torch.manual_seed`.
    dtype : torch.dtype, default=torch.float32
        Real floating-point output and random-draw dtype.
    device : torch.device or str, optional
        Allocation and random-draw device (CPU by default).

    Returns
    -------
    torch.Tensor
        Dense `(n, n)` recurrent matrix on the requested dtype/device, with
        spectral radius approximately equal to `spectral_radius`.

    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.
    """
    target = matrix_device(n, dtype, device)
    spectral_radius = finite_scalar(spectral_radius, "spectral_radius")
    if spectral_radius < 0:
        raise ValueError(f"spectral_radius must be non-negative, got {spectral_radius}")

    generator = seeded_generator(seed, target)

    # Half-width of the uniform distribution that yields the target spectral
    # radius under the circular law (variance a^2/3, radius ~ sqrt(n) * a/sqrt(3)).
    half_width = spectral_radius * math.sqrt(3.0 / n)

    matrix = torch.empty(n, n, dtype=dtype, device=target)
    matrix.uniform_(-half_width, half_width, generator=generator)

    return matrix

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

gain

Scaling factor applied to the orthogonal matrix. With abs(gain)=1 all singular values are 1 (norm-preserving). Since the layer-level spectral_radius rescale is suppressed (pre-scaled topology), gain is the only knob on the overall scale.

TYPE: float DEFAULT: 1.0

seed

Seed for the Gaussian draw. None uses the global torch RNG.

TYPE: int DEFAULT: None

dtype

Real floating-point output dtype. CPU QR retains float64 precision; accelerator QR uses the requested dtype, promoting half to float32.

TYPE: dtype DEFAULT: torch.float32

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.

TYPE: device or str DEFAULT: None

RETURNS DESCRIPTION
Tensor

Dense orthogonal matrix of shape (n, n) (times gain). Setup costs O(n³); storage and dense matrix-vector multiplication cost O(n²).

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
@register_matrix_topology("orthogonal", prescaled=True)
def orthogonal_matrix(
    n: int,
    gain: float = 1.0,
    seed: int | None = None,
    *,
    dtype: torch.dtype = torch.float32,
    device: torch.device | str | None = None,
) -> torch.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.

    Parameters
    ----------
    n : int
        Matrix size (number of reservoir units).
    gain : float, default=1.0
        Scaling factor applied to the orthogonal matrix. With `abs(gain)=1` all
        singular values are 1 (norm-preserving). Since the layer-level
        `spectral_radius` rescale is suppressed (pre-scaled topology),
        `gain` is the only knob on the overall scale.
    seed : int, optional
        Seed for the Gaussian draw. `None` uses the global torch RNG.
    dtype : torch.dtype, default=torch.float32
        Real floating-point output dtype. CPU QR retains float64 precision;
        accelerator QR uses the requested dtype, promoting half to float32.
    device : torch.device or str, optional
        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
    -------
    torch.Tensor
        Dense orthogonal matrix of shape `(n, n)` (times `gain`). Setup
        costs O(n³); storage and dense matrix-vector multiplication cost O(n²).

    Examples
    --------
    >>> from resdag.layers import ESNLayer
    >>> reservoir = ESNLayer(500, feedback_size=3, topology="orthogonal")
    >>> reservoir = ESNLayer(
    ...     500, feedback_size=3, topology=("orthogonal", {"seed": 42})
    ... )
    """
    target = matrix_device(n, dtype, device)
    gain = finite_scalar(gain, "gain")
    generator = seeded_generator(seed, target)
    # Retain the historical high-precision CPU draw. Accelerators compute in
    # the requested dtype (promoting half precision for QR).
    compute_dtype = torch.float64 if target.type == "cpu" else working_dtype(dtype)
    q = haar_orthogonal(n, dtype=compute_dtype, device=target, generator=generator)
    return (gain * q).to(dtype=dtype)

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

cycle_weight

Constant weight of the cycle edges.

TYPE: float DEFAULT: 0.1

self_loop_weight

Weight on every diagonal self-connection. For n > 1, eigenvalues are those of the cycle shifted by this value.

TYPE: float DEFAULT: 0.1

dtype

Real floating-point output dtype.

TYPE: dtype DEFAULT: torch.float32

device

Allocation device (CPU by default).

TYPE: device or str DEFAULT: None

RETURNS DESCRIPTION
Tensor

Dense (n, n) cycle with diagonal self-loops.

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
@register_matrix_topology("self_loop_cycle", cycle_weight=0.1, self_loop_weight=0.1)
def self_loop_cycle(
    n: int,
    cycle_weight: float = 0.1,
    self_loop_weight: float = 0.1,
    *,
    dtype: torch.dtype = torch.float32,
    device: torch.device | str | None = None,
) -> torch.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.

    Parameters
    ----------
    n : int
        Number of reservoir units, a positive integer.
    cycle_weight : float, default=0.1
        Constant weight of the cycle edges.
    self_loop_weight : float, default=0.1
        Weight on every diagonal self-connection. For `n > 1`, eigenvalues
        are those of the cycle shifted by this value.
    dtype : torch.dtype, default=torch.float32
        Real floating-point output dtype.
    device : torch.device or str, optional
        Allocation device (CPU by default).

    Returns
    -------
    torch.Tensor
        Dense `(n, n)` cycle with diagonal self-loops.

    Raises
    ------
    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.
    """
    target = matrix_device(n, dtype, device)
    matrix = _build_simple_cycle(n, float(cycle_weight), dtype=dtype, device=target)
    matrix.fill_diagonal_(float(self_loop_weight))
    return matrix

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

weight

Constant weight on every cycle edge. The raw spectral radius is abs(weight). A layer's requested radius changes this overall scale.

TYPE: float DEFAULT: 0.1

dtype

Real floating-point output dtype.

TYPE: dtype DEFAULT: torch.float32

device

Allocation device (CPU by default).

TYPE: device or str DEFAULT: None

RETURNS DESCRIPTION
Tensor

Dense (n, n) cyclic matrix; a subdiagonal plus wrap-around corner.

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
@register_matrix_topology("simple_cycle", weight=0.1)
def simple_cycle(
    n: int,
    weight: float = 0.1,
    *,
    dtype: torch.dtype = torch.float32,
    device: torch.device | str | None = None,
) -> torch.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.

    Parameters
    ----------
    n : int
        Number of reservoir units, a positive integer. One gives a self-loop.
    weight : float, default=0.1
        Constant weight on every cycle edge. The raw spectral radius is
        `abs(weight)`. A layer's requested radius changes this overall scale.
    dtype : torch.dtype, default=torch.float32
        Real floating-point output dtype.
    device : torch.device or str, optional
        Allocation device (CPU by default).

    Returns
    -------
    torch.Tensor
        Dense `(n, n)` cyclic matrix; a subdiagonal plus wrap-around corner.

    Raises
    ------
    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.
    """
    target = matrix_device(n, dtype, device)
    return _build_simple_cycle(n, float(weight), dtype=dtype, device=target)

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

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: sequence of float or torch.Tensor DEFAULT: None

seed

Local RNG seed. Repeated calls with the same seed, device, dtype, and parameters produce the same matrix without changing global RNG.

TYPE: int DEFAULT: None

dtype

Real floating-point output dtype. Float64 computations retain the supplied double precision; half/bfloat16 QR is promoted to float32.

TYPE: dtype DEFAULT: torch.float32

device

Output device (CPU by default). MPS QR uses a CPU fallback.

TYPE: device or str DEFAULT: None

RETURNS DESCRIPTION
Tensor

Dense (n, n) real matrix with the specified singular values, up to numerical precision. Setup is O(n³); storage is O(n²).

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
@register_matrix_topology("singular_spectrum", prescaled=True)
def singular_spectrum(
    n: int,
    singular_values: Sequence[float] | torch.Tensor | None = None,
    seed: int | None = None,
    *,
    dtype: torch.dtype = torch.float32,
    device: torch.device | str | None = None,
) -> torch.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.

    Parameters
    ----------
    n : int
        Matrix size, a positive integer.
    singular_values : sequence of float or torch.Tensor, optional
        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.
    seed : int, optional
        Local RNG seed. Repeated calls with the same seed, device, dtype,
        and parameters produce the same matrix without changing global RNG.
    dtype : torch.dtype, default=torch.float32
        Real floating-point output dtype. Float64 computations retain the
        supplied double precision; half/bfloat16 QR is promoted to float32.
    device : torch.device or str, optional
        Output device (CPU by default). MPS QR uses a CPU fallback.

    Returns
    -------
    torch.Tensor
        Dense `(n, n)` real matrix with the specified singular values, up
        to numerical precision. Setup is O(n³); storage is O(n²).

    Raises
    ------
    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,
    ...     ),
    ... )
    """
    target = matrix_device(n, dtype, device)
    compute_dtype = working_dtype(dtype)
    if singular_values is None:
        values = torch.linspace(1.0, 0.1, n, dtype=compute_dtype, device=target)
    else:
        raw = torch.as_tensor(singular_values)
        if raw.is_complex():
            raise ValueError("singular_values must be real, finite, and nonnegative")
        values = torch.as_tensor(singular_values, dtype=compute_dtype, device=target)
    if values.ndim != 1 or values.numel() != n:
        raise ValueError(f"singular_values must contain exactly n={n} values")
    if not bool(torch.isfinite(values).all()) or bool((values < 0).any()):
        raise ValueError("singular_values must be real, finite, and nonnegative")

    generator = seeded_generator(seed, target)
    u = haar_orthogonal(n, dtype=compute_dtype, device=target, generator=generator)
    v = haar_orthogonal(n, dtype=compute_dtype, device=target, generator=generator)
    return ((u * values) @ v.T).to(dtype=dtype)

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

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: sequence of complex or torch.Tensor DEFAULT: None

seed

Seed of the local RNG used for the orthogonal similarity factor. None draws from the global torch RNG.

TYPE: int DEFAULT: None

dtype

Real floating-point output dtype. Float64 retains double precision; half/bfloat16 QR is computed in float32 then cast.

TYPE: dtype DEFAULT: torch.float32

device

Output device (CPU by default). MPS QR uses a CPU fallback.

TYPE: device or str DEFAULT: None

RETURNS DESCRIPTION
Tensor

Dense real normal (n, n) matrix whose eigenvalues equal the supplied values up to numerical precision. Setup is O(n³), storage O(n²).

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
@register_matrix_topology("eigen_spectrum", prescaled=True)
def eigen_spectrum(
    n: int,
    eigenvalues: Sequence[complex] | torch.Tensor | None = None,
    seed: int | None = None,
    *,
    dtype: torch.dtype = torch.float32,
    device: torch.device | str | None = None,
) -> torch.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)`.

    Parameters
    ----------
    n : int
        Matrix size, a positive integer.
    eigenvalues : sequence of complex or torch.Tensor, optional
        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.
    seed : int, optional
        Seed of the local RNG used for the orthogonal similarity factor.
        None draws from the global torch RNG.
    dtype : torch.dtype, default=torch.float32
        Real floating-point output dtype. Float64 retains double precision;
        half/bfloat16 QR is computed in float32 then cast.
    device : torch.device or str, optional
        Output device (CPU by default). MPS QR uses a CPU fallback.

    Returns
    -------
    torch.Tensor
        Dense real normal `(n, n)` matrix whose eigenvalues equal the
        supplied values up to numerical precision. Setup is O(n³), storage O(n²).

    Raises
    ------
    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,
    ...     ),
    ... )
    """
    target = matrix_device(n, dtype, device)
    blocks = _real_spectral_blocks(n, eigenvalues)
    compute_dtype = working_dtype(dtype)
    block_matrix = torch.zeros(n, n, dtype=compute_dtype, device=target)
    position = 0
    for real, imaginary in blocks:
        block_matrix[position, position] = real
        if imaginary:
            block_matrix[position + 1, position + 1] = real
            block_matrix[position, position + 1] = -imaginary
            block_matrix[position + 1, position] = imaginary
            position += 2
        else:
            position += 1
    generator = seeded_generator(seed, target)
    q = haar_orthogonal(n, dtype=compute_dtype, device=target, generator=generator)
    return (q @ block_matrix @ q.T).to(dtype=dtype)

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

gain

Finite multiplier on the signed permutation. All singular values equal abs(gain). Zero gives an all-zero matrix; negative gains are valid.

TYPE: float DEFAULT: 1.0

seed

Local seed for the random permutation and signs. None uses torch's global RNG; an explicit seed leaves the global RNG unchanged.

TYPE: int DEFAULT: None

dtype

Real floating-point output dtype.

TYPE: dtype DEFAULT: torch.float32

device

Allocation and random-draw device (CPU by default).

TYPE: device or str DEFAULT: None

RETURNS DESCRIPTION
Tensor

Dense (n, n) matrix for direct callers. Sparse ESN initialization bypasses this dense materialization while preserving the same draws.

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
@register_matrix_topology("signed_permutation", prescaled=True)
def signed_permutation(
    n: int,
    gain: float = 1.0,
    seed: int | None = None,
    *,
    dtype: torch.dtype = torch.float32,
    device: torch.device | str | None = None,
) -> torch.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.

    Parameters
    ----------
    n : int
        Matrix size, a positive integer.
    gain : float, default=1.0
        Finite multiplier on the signed permutation. All singular values
        equal abs(gain). Zero gives an all-zero matrix; negative gains are valid.
    seed : int, optional
        Local seed for the random permutation and signs. None uses torch's
        global RNG; an explicit seed leaves the global RNG unchanged.
    dtype : torch.dtype, default=torch.float32
        Real floating-point output dtype.
    device : torch.device or str, optional
        Allocation and random-draw device (CPU by default).

    Returns
    -------
    torch.Tensor
        Dense `(n, n)` matrix for direct callers. Sparse ESN initialization
        bypasses this dense materialization while preserving the same draws.

    Raises
    ------
    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}),
    ... )
    """
    target = matrix_device(n, dtype, device)
    gain = finite_scalar(gain, "gain")
    generator = seeded_generator(seed, target)
    columns = torch.randperm(n, generator=generator, device=target)
    signs = torch.randint(0, 2, (n,), generator=generator, device=target).to(dtype)
    signs = signs.mul_(2).sub_(1).mul_(gain)
    matrix = torch.zeros(n, n, dtype=dtype, device=target)
    matrix[torch.arange(n, device=target), columns] = signs
    return matrix

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

gain

Finite multiplier. All singular values equal abs(gain); zero and negative gains are allowed.

TYPE: float DEFAULT: 1.0

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

seed

Local seed for Gaussian reflection directions on the requested device. None uses torch's global RNG.

TYPE: int DEFAULT: None

dtype

Real floating-point output dtype. Half/bfloat16 arithmetic is promoted to float32 before the final cast.

TYPE: dtype DEFAULT: torch.float32

device

Allocation, random-draw, and computation device (CPU by default).

TYPE: device or str DEFAULT: None

RETURNS DESCRIPTION
Tensor

Dense scaled orthogonal (n, n) matrix. Construction costs O(reflectors * n²), and dense storage/application cost O(n²).

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
@register_matrix_topology("householder_orthogonal", prescaled=True)
def householder_orthogonal(
    n: int,
    gain: float = 1.0,
    reflectors: int | None = None,
    seed: int | None = None,
    *,
    dtype: torch.dtype = torch.float32,
    device: torch.device | str | None = None,
) -> torch.Tensor:
    r"""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.

    Parameters
    ----------
    n : int
        Matrix size, a positive integer.
    gain : float, default=1.0
        Finite multiplier. All singular values equal abs(gain); zero and
        negative gains are allowed.
    reflectors : int or None, default=None
        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.
    seed : int, optional
        Local seed for Gaussian reflection directions on the requested
        device. None uses torch's global RNG.
    dtype : torch.dtype, default=torch.float32
        Real floating-point output dtype. Half/bfloat16 arithmetic is
        promoted to float32 before the final cast.
    device : torch.device or str, optional
        Allocation, random-draw, and computation device (CPU by default).

    Returns
    -------
    torch.Tensor
        Dense scaled orthogonal `(n, n)` matrix. Construction costs
        O(reflectors * n²), and dense storage/application cost O(n²).

    Raises
    ------
    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}),
    ... )
    """
    target = matrix_device(n, dtype, device)
    gain = finite_scalar(gain, "gain")
    count = n if reflectors is None else reflectors
    if isinstance(count, bool) or not isinstance(count, int) or count < 0:
        raise ValueError(f"reflectors must be a nonnegative integer or None, got {reflectors}")
    compute_dtype = working_dtype(dtype)
    generator = seeded_generator(seed, target)
    matrix = torch.eye(n, dtype=compute_dtype, device=target)
    directions = torch.randn(count, n, generator=generator, dtype=compute_dtype, device=target)
    directions = directions / directions.norm(dim=1, keepdim=True).clamp_min(
        torch.finfo(compute_dtype).tiny
    )
    for direction in directions:
        matrix = matrix - 2 * torch.outer(direction, direction @ matrix)
    return (gain * matrix).to(dtype=dtype)

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

weight

Main-diagonal weight and the scale of every other diagonal.

TYPE: float DEFAULT: 0.1

decay

Geometric factor per diagonal offset. decay=1 fills each diagonal with the same weight; 0 < decay < 1 weakens distant connections. The sign alternates across offsets when decay is negative.

TYPE: float DEFAULT: 1.0

bandwidth

Maximum populated absolute offset. Must be nonnegative when supplied; None keeps every diagonal. Zero gives a scaled identity.

TYPE: int or None DEFAULT: None

dtype

Real floating-point output and power-computation dtype.

TYPE: dtype DEFAULT: torch.float32

device

Allocation and computation device (CPU by default).

TYPE: device or str DEFAULT: None

RETURNS DESCRIPTION
Tensor

Dense (n, n) symmetric Toeplitz matrix with optional band masking.

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
@register_matrix_topology("toeplitz", weight=0.1, decay=1.0, bandwidth=None)
def toeplitz(
    n: int,
    weight: float = 0.1,
    decay: float = 1.0,
    bandwidth: int | None = None,
    *,
    dtype: torch.dtype = torch.float32,
    device: torch.device | str | None = None,
) -> torch.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.

    Parameters
    ----------
    n : int
        Number of reservoir units, a positive integer.
    weight : float, default=0.1
        Main-diagonal weight and the scale of every other diagonal.
    decay : float, default=1.0
        Geometric factor per diagonal offset. `decay=1` fills each diagonal
        with the same weight; `0 < decay < 1` weakens distant connections.
        The sign alternates across offsets when decay is negative.
    bandwidth : int or None, default=None
        Maximum populated absolute offset. Must be nonnegative when supplied;
        None keeps every diagonal. Zero gives a scaled identity.
    dtype : torch.dtype, default=torch.float32
        Real floating-point output and power-computation dtype.
    device : torch.device or str, optional
        Allocation and computation device (CPU by default).

    Returns
    -------
    torch.Tensor
        Dense `(n, n)` symmetric Toeplitz matrix with optional band masking.

    Raises
    ------
    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}),
    ... )
    """
    target = matrix_device(n, dtype, device)
    if bandwidth is not None and bandwidth < 0:
        raise ValueError(f"bandwidth must be non-negative, got {bandwidth}")
    rows = torch.arange(n, device=target).view(n, 1)
    cols = torch.arange(n, device=target).view(1, n)
    offset = (cols - rows).abs()
    matrix = float(weight) * (float(decay) ** offset.to(dtype))
    if bandwidth is not None:
        matrix = torch.where(offset <= bandwidth, matrix, torch.zeros_like(matrix))
    return matrix

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
)

RecurrentInitializerSpec module-attribute

RecurrentInitializerSpec = TopologySpec

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 parameters
  • tuple[str, dict] — registry name with parameter overrides
  • callable — any matrix builder fn(n, **kw) -> matrix | graph or in-place fn(tensor, **kw); wrapped in MatrixTopology
  • tuple[callable, dict] — matrix builder with bound parameters
  • TopologyInitializer — already resolved, returned as-is
PARAMETER DESCRIPTION
spec

Topology specification in one of the accepted formats.

TYPE: TopologySpec

seed

Seed forwarded to the underlying builder for reproducibility. It is applied only to the str, tuple[str, dict], callable, and tuple[callable, dict] forms, only when the builder accepts a seed argument, and only when the spec did not already pin one (an explicit spec seed always wins). A torch.Generator is reduced to its initial_seed() before use. Pre-resolved TopologyInitializer objects are returned untouched.

TYPE: int or Generator DEFAULT: None

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
def 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 parameters
    - `tuple[str, dict]` — registry name with parameter overrides
    - `callable` — any matrix builder `fn(n, **kw) -> matrix | graph` or
      in-place `fn(tensor, **kw)`; wrapped in `MatrixTopology`
    - `tuple[callable, dict]` — matrix builder with bound parameters
    - `TopologyInitializer` — already resolved, returned as-is

    Parameters
    ----------
    spec : TopologySpec
        Topology specification in one of the accepted formats.
    seed : int or torch.Generator, optional
        Seed forwarded to the underlying builder for reproducibility. It is
        applied only to the `str`, `tuple[str, dict]`, `callable`, and
        `tuple[callable, dict]` forms, only when the builder accepts a
        `seed` argument, and only when the spec did not already pin one (an
        explicit spec seed always wins). A `torch.Generator` is reduced
        to its `initial_seed()` before use. Pre-resolved
        `TopologyInitializer` objects are returned untouched.

    Returns
    -------
    TopologyInitializer or None
        Resolved topology object, or None if spec was None.

    Raises
    ------
    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(...)
    """
    seed = coerce_seed_to_int(seed)
    if spec is None:
        return None
    if isinstance(spec, TopologyInitializer):
        return spec
    if isinstance(spec, str):
        topology = get_topology(spec)
        builder = _topology_builder(topology)
        if builder is not None and _accepts_seed(builder) and seed is not None:
            return get_topology(spec, seed=seed)
        if isinstance(topology, MatrixTopology) and builder is not None:
            if seed is not None:
                topology.seed = _generator_seed(builder, {}, seed)
        return topology
    if isinstance(spec, tuple):
        name, params = spec
        if callable(name):
            return MatrixTopology(
                name,
                _callback_kwargs(name, dict(params), seed),
                seed=_generator_seed(name, dict(params), seed),
            )
        if name not in _TOPOLOGY_REGISTRY:
            return get_topology(name, **dict(params))
        builder = _TOPOLOGY_REGISTRY[name][0]
        injected = (
            _inject_seed(dict(params), builder, seed) if builder is not None else dict(params)
        )
        topology = get_topology(name, **injected)
        if isinstance(topology, MatrixTopology) and builder is not None:
            topology.seed = _generator_seed(builder, dict(params), seed)
        return topology
    if callable(spec):
        return MatrixTopology(
            spec, _callback_kwargs(spec, {}, seed), seed=_generator_seed(spec, {}, seed)
        )
    raise TypeError(
        f"Invalid topology spec type: {type(spec).__name__}. "
        f"Expected str, callable, tuple[str | callable, dict], or TopologyInitializer."
    )

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 parameters
  • tuple[str, dict] — registry name with parameter overrides
  • callable — any matrix builder fn(rows, cols, **kw) -> matrix or in-place fn(tensor, **kw); wrapped in FunctionInitializer
  • tuple[callable, dict] — matrix builder with bound parameters
  • InputFeedbackInitializer — already resolved, returned as-is
PARAMETER DESCRIPTION
spec

Initializer specification in one of the accepted formats.

TYPE: InitializerSpec

seed

Seed forwarded to the underlying initializer for reproducibility. It is applied only to the str, tuple[str, dict], callable, and tuple[callable, dict] forms, only when the initializer accepts a seed argument, and only when the spec did not already pin one (an explicit spec seed always wins). A torch.Generator is reduced to its initial_seed() before use. Pre-resolved InputFeedbackInitializer objects are returned untouched.

TYPE: int or Generator DEFAULT: None

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
def 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 parameters
    - `tuple[str, dict]` — registry name with parameter overrides
    - `callable` — any matrix builder `fn(rows, cols, **kw) -> matrix` or
      in-place `fn(tensor, **kw)`; wrapped in `FunctionInitializer`
    - `tuple[callable, dict]` — matrix builder with bound parameters
    - `InputFeedbackInitializer` — already resolved, returned as-is

    Parameters
    ----------
    spec : InitializerSpec
        Initializer specification in one of the accepted formats.
    seed : int or torch.Generator, optional
        Seed forwarded to the underlying initializer for reproducibility. It
        is applied only to the `str`, `tuple[str, dict]`, `callable`,
        and `tuple[callable, dict]` forms, only when the initializer accepts
        a `seed` argument, and only when the spec did not already pin one (an
        explicit spec seed always wins). A `torch.Generator` is reduced
        to its `initial_seed()` before use. Pre-resolved
        `InputFeedbackInitializer` objects are returned untouched.

    Returns
    -------
    InputFeedbackInitializer or None
        Resolved initializer object, or None if spec was None.

    Raises
    ------
    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(...)
    """
    seed = coerce_seed_to_int(seed)
    if spec is None:
        return None
    if isinstance(spec, InputFeedbackInitializer):
        return spec
    if isinstance(spec, str):
        initializer = get_input_feedback(spec)
        target = _initializer_seed_target(initializer)
        if _accepts_seed(target) and seed is not None:
            return get_input_feedback(spec, seed=seed)
        if isinstance(initializer, FunctionInitializer):
            if seed is not None:
                initializer._generator_seed = _generator_seed(initializer.fn, {}, seed)
        return initializer
    if isinstance(spec, tuple):
        name, params = spec
        if callable(name):
            return _function_initializer(name, dict(params), seed)
        if name not in _INPUT_FEEDBACK_REGISTRY:
            return get_input_feedback(name, **dict(params))
        # Inspect the registered constructor, without constructing invalid
        # defaults before the caller's required options have been supplied.
        target = _INPUT_FEEDBACK_REGISTRY[name][0]
        injected = _inject_seed(dict(params), target, seed)
        initializer = get_input_feedback(name, **injected)
        if isinstance(initializer, FunctionInitializer):
            initializer._generator_seed = _generator_seed(initializer.fn, dict(params), seed)
        return initializer
    if callable(spec):
        return _function_initializer(spec, {}, seed)
    raise TypeError(
        f"Invalid initializer spec type: {type(spec).__name__}. "
        f"Expected str, callable, tuple[str | callable, dict], or InputFeedbackInitializer."
    )

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
def 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.
    """
    return resolve_topology(spec, seed=seed)

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
def 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.
    """
    if topology is not None and recurrent_initializer is not None:
        raise ValueError("Specify only one of topology and recurrent_initializer, not both.")
    return recurrent_initializer if recurrent_initializer is not None else topology