Skip to content

Low-memory LSMR readout

Choose readout="lsmr" when the readout's feature-by-feature matrix would be too large to form. It solves the same ridge problem as the other L2 readouts, using SciPy's established iterative solver. Automatic solver selection stays unchanged; LSMR is an explicit choice.

import torch
import resdag as rd

t = torch.arange(400, dtype=torch.float64) * 0.05
train = torch.stack((t.sin(), t.cos()), dim=-1)
model = rd.ESN(
    32, input_size=2, washout=30, seed=7, dtype=torch.float64,
    readout="lsmr", alpha=1e-5,
    readout_kwargs={
        "atol": 1e-10, "btol": 1e-10,
        "max_iter": 500, "chunk_size": 128,
    },
).fit(train)
prediction = model.forecast(horizon=40)
assert prediction.shape == (40, 2)
assert torch.isfinite(prediction).all()

head = next(layer for layer in model.graph.modules()
            if isinstance(layer, rd.LSMRReadoutLayer))
for column in head.last_solve.columns:
    print(column.output, column.stop_reason, column.iterations)

Custom DAGs use rd.LSMRReadoutLayer(features, outputs, ...) like any other readout. Built-in vanilla and OTT models also retain this solver and its settings when tuning rebuilds candidates. model.save(...) and rd.load(...) preserve fitted weights, options and reservoir memory. Past solve diagnostics are runtime metadata and start as None after loading.

What memory it saves

LSMR calls a scipy.sparse.linalg.LinearOperator that computes products with the feature matrix and its transpose. It never forms X.T @ X, an augmented identity, or an SVD/QR decomposition. When fitting an intercept, it centers row blocks on demand rather than retaining a second complete centered design.

The feature matrix still exists. Fitting needs a CPU float64 representation of it, up to min(chunk_size, samples) * features temporary centered entries, fitted coefficients and linear-size solver vectors. A short series may fit inside one block. Reducing chunk_size lowers centering scratch storage but can increase operator overhead. Reservoir projections and collected states are still produced by the ordinary batch fitting path; this option does not make the whole DAG streaming. See streaming training when the sequence's feature history is the limiting allocation.

Numerical controls

The fitted objective is

\[ \min_{W,b}\;\lVert XW+b-Y\rVert_F^2+\alpha\lVert W\rVert_F^2. \]

The data-fit term uses the sum of squared errors, rather than their mean. SciPy receives damp=sqrt(alpha). The intercept is unpenalized: supervised feature and target means are removed during the solve, then restored in the fitted bias. With bias=False, no centering or intercept is applied. Each target column is scaled internally and restored afterwards so changing small target units does not accidentally make the zero solution pass a relative stopping test.

Option Default Meaning
alpha 1e-6 Finite non-negative ridge penalty; never increased automatically
atol, btol 1e-8 Non-negative SciPy backward-error stopping tolerances
conlim 1e8 Estimated condition limit; zero disables this limit
max_iter 1000 Iteration budget per output; None uses SciPy's min(samples, features)
chunk_size 1024 Maximum rows centered at once
cpu_fallback True Permit the warned CPU solve for accelerator inputs

Iteration exhaustion, a condition-limit stop, or non-finite results raise before new coefficients are published. A failed first fit stays unfitted; a failed refit retains its previous fitted weights. Increase the iteration budget when a valid but difficult problem needs more iterations. For very ill-conditioned data, compare against a direct SVD solve and evaluate held-out forecasts. Convergence is a numerical stopping result, not a guarantee of accurate coefficients or long autonomous predictions.

last_solve records input placement, the CPU float64 solve, matrix dimensions and a report per output. Per-output norms describe the normalized-target solve; target_scale explains the conversion back to original units. Condition numbers are estimates. Different solvers' conditioning estimates need not use the same norm or matrix.

Devices and PyTorch integration

When tuning with a memory budget, the default planner still reserves general direct-solver workspaces. A custom memory_estimator can describe LSMR's tighter requirements; see memory and sparse models.

Fitting runs on CPU in float64. Accelerator feature tensors are copied to CPU with a RuntimeWarning; pass cpu_fallback=False to reject that transfer. Fitted coefficients return to the layer's device and dtype. This explicit bridge can cost time and host memory, so measure it for your workload.

After fitting, forward evaluation is the usual Torch linear layer. It can sit inside a larger PyTorch model, passes gradients to earlier layers, and supports trainable=True when fitted readout weights should also receive gradient updates. The algebraic fit itself is not differentiated through SciPy.

API

LSMRReadoutLayer

LSMRReadoutLayer(
    in_features: int,
    out_features: int,
    bias: bool = True,
    name: str | None = None,
    trainable: bool = False,
    alpha: float = 1e-06,
    atol: float = 1e-08,
    btol: float = 1e-08,
    conlim: float = 100000000.0,
    max_iter: int | None = 1000,
    chunk_size: int = 1024,
    cpu_fallback: bool = True,
)

Bases: ReadoutLayer

Fit ||X W + b - Y||² + alpha ||W||² without a Gram matrix.

This explicit solver uses SciPy LinearOperator and lsmr on CPU in float64, one output at a time. damp=sqrt(alpha) preserves the requested ridge penalty. With a bias, row blocks are centered on demand and the unpenalized intercept is recovered afterwards. Targets are scaled per output to keep tiny target magnitudes meaningful to relative stopping tests.

The supplied feature matrix remains resident. Working storage additionally includes its CPU float64 representation, at most chunk_size * in_features centered scratch entries and linear-size solver vectors. This avoids a feature-by-feature Gram matrix, QR augmentation and a complete retained centered design; it does not make reservoir feature extraction streaming.

Accelerator inputs require an explicit CPU bridge: the default cpu_fallback=True allows it with a warning, while False rejects the transfer. Fitted parameters remain on the layer's device and dtype; ordinary forward calls are Torch operations and retain upstream gradients.

PARAMETER DESCRIPTION
in_features

Feature and prediction widths.

TYPE: int

out_features

Feature and prediction widths.

TYPE: int

bias

Fit an unpenalized intercept by centering the supervised rows.

TYPE: bool DEFAULT: True

name

Readout name for custom DAG training targets.

TYPE: str DEFAULT: None

trainable

Allow gradient updates of fitted readout parameters after fitting.

TYPE: bool DEFAULT: False

alpha

Finite non-negative L2 penalty; never increased automatically.

TYPE: float DEFAULT: 1e-6

atol

Finite non-negative SciPy backward-error stopping tolerances. These are relative tests, not the absolute residual cutoff used by CGReadoutLayer.

TYPE: float DEFAULT: 1e-8

btol

Finite non-negative SciPy backward-error stopping tolerances. These are relative tests, not the absolute residual cutoff used by CGReadoutLayer.

TYPE: float DEFAULT: 1e-8

conlim

Finite non-negative estimated condition limit. Zero disables this limit.

TYPE: float DEFAULT: 1e8

max_iter

Positive iteration budget per output. None uses SciPy's min(N, F). Exhaustion or a condition-limit stop raises without publishing weights.

TYPE: int or None DEFAULT: 1000

chunk_size

Maximum rows centered in scratch storage during each operator product.

TYPE: int DEFAULT: 1024

cpu_fallback

Permit the warned CPU float64 bridge for accelerator feature tensors.

TYPE: bool DEFAULT: True

ATTRIBUTE DESCRIPTION
last_solve

Diagnostics from the last successful solve. Reports are runtime metadata and are not preserved in portable checkpoints.

TYPE: LSMRSolveReport or None

Source code in src/resdag/layers/readouts/lsmr_readout.py
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
def __init__(
    self,
    in_features: int,
    out_features: int,
    bias: bool = True,
    name: str | None = None,
    trainable: bool = False,
    alpha: float = 1e-6,
    atol: float = 1e-8,
    btol: float = 1e-8,
    conlim: float = 1e8,
    max_iter: int | None = 1000,
    chunk_size: int = 1024,
    cpu_fallback: bool = True,
) -> None:
    super().__init__(in_features, out_features, bias, name, trainable)
    self.alpha, self.atol, self.btol = alpha, atol, btol
    self.conlim, self.max_iter = conlim, max_iter
    self.chunk_size, self.cpu_fallback = chunk_size, cpu_fallback
    self.last_solve: LSMRSolveReport | None = None
    self._validate_options()

solve

solve(states: Tensor, targets: Tensor) -> tuple[Tensor, Tensor | None]

Solve validated flattened features without publishing partial output fits.

Source code in src/resdag/layers/readouts/lsmr_readout.py
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
def solve(
    self, states: torch.Tensor, targets: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor | None]:
    """Solve validated flattened features without publishing partial output fits."""
    from scipy.sparse.linalg import lsmr

    self._validate_options()
    bridge = states.device.type != "cpu"
    if bridge:
        if not self.cpu_fallback:
            raise RuntimeError(
                "LSMRReadoutLayer requires CPU float64 fitting; cpu_fallback=False"
            )
        warnings.warn(
            "LSMRReadoutLayer: copying features/targets to CPU float64 for SciPy fitting; "
            "fitted parameters remain on their original device.",
            RuntimeWarning,
            stacklevel=2,
        )
    # Transfer before casting: MPS cannot create even a transient float64
    # tensor while resolving a combined device/dtype conversion.
    x = states.detach().cpu().double().numpy()
    y = targets.detach().cpu().double().numpy()
    mean_x = x.mean(axis=0) if self.bias is not None else None
    mean_y = y.mean(axis=0) if self.bias is not None else np.zeros(y.shape[1])
    if (mean_x is not None and not np.isfinite(mean_x).all()) or not np.isfinite(mean_y).all():
        raise RuntimeError(
            "LSMRReadoutLayer centering exceeded float64 range; rescale the data"
        )
    operator = _centered_operator(x, mean_x, self.chunk_size)
    coefficients = np.empty((x.shape[1], y.shape[1]), dtype=np.float64)
    reports = []
    for output in range(y.shape[1]):
        rhs = y[:, output] - mean_y[output]
        scale = float(np.max(np.abs(rhs)))
        if not math.isfinite(scale):
            raise RuntimeError(
                "LSMRReadoutLayer targets exceeded float64 range; rescale the data"
            )
        normalized = rhs / scale if scale else rhs
        result = lsmr(
            operator,
            normalized,
            damp=math.sqrt(self.alpha),
            atol=self.atol,
            btol=self.btol,
            conlim=self.conlim,
            maxiter=self.max_iter,
        )
        weights, stop, iterations, normr, normar, norma, conda, normx = result
        reason = _STOP_REASONS.get(stop, "unknown stopping reason")
        if (
            stop not in _ACCEPTED_STOPS
            or not all(
                math.isfinite(value) and value >= 0
                for value in (normr, normar, norma, conda, normx)
            )
            or not np.isfinite(weights).all()
        ):
            raise RuntimeError(
                f"LSMRReadoutLayer output {output}: {reason} (stop={stop}, "
                f"iterations={iterations}, condition={conda:g}); no weights were published. "
                "Adjust tolerances, max_iter/conlim, scaling, or choose a direct solver."
            )
        if stop == 0 and np.any(operator.rmatvec(normalized) != 0):
            raise RuntimeError(
                "LSMRReadoutLayer reported a zero solution for a nonzero normal residual; "
                "rescale features to avoid float64 norm underflow."
            )
        coefficients[:, output] = weights * scale
        reports.append(
            LSMRColumnReport(
                output,
                int(stop),
                reason,
                int(iterations),
                float(normr),
                float(normar),
                float(norma),
                float(conda),
                float(normx),
                scale,
            )
        )
    intercept = mean_y - mean_x @ coefficients if mean_x is not None else None
    if not np.isfinite(coefficients).all() or (
        intercept is not None and not np.isfinite(intercept).all()
    ):
        raise RuntimeError(
            "LSMRReadoutLayer produced non-finite coefficients; rescale the data"
        )
    coefs = torch.from_numpy(coefficients).to(dtype=states.dtype).to(device=states.device)
    bias = (
        torch.from_numpy(intercept).to(dtype=states.dtype).to(device=states.device)
        if intercept is not None
        else None
    )
    if not torch.isfinite(coefs).all() or (bias is not None and not torch.isfinite(bias).all()):
        raise RuntimeError("LSMRReadoutLayer coefficients exceed the input dtype range")
    self.last_solve = LSMRSolveReport(
        float(self.alpha),
        str(states.device),
        states.dtype,
        "cpu",
        torch.float64,
        x.shape[0],
        x.shape[1],
        self.chunk_size,
        bridge,
        tuple(reports),
    )
    return coefs, bias

LSMRSolveReport dataclass

LSMRSolveReport(
    alpha: float,
    input_device: str,
    input_dtype: dtype,
    solve_device: str,
    solve_dtype: dtype,
    n_samples: int,
    n_features: int,
    chunk_size: int,
    cpu_bridge: bool,
    columns: tuple[LSMRColumnReport, ...],
)

Diagnostics from the last successful LSMR solve; not checkpoint state.

LSMRColumnReport dataclass

LSMRColumnReport(
    output: int,
    stop_code: int,
    stop_reason: str,
    iterations: int,
    residual_norm: float,
    normal_residual_norm: float,
    operator_norm: float,
    condition_estimate: float,
    solution_norm: float,
    target_scale: float,
)

One output's solve against a unit-scaled target, before parameter casting.

Residual/operator/solution norms are SciPy's diagnostics for that normalized system. Multiply the solution by target_scale to recover original units. Condition estimates and stopping tests do not guarantee forecast accuracy.

See SciPy's LSMR documentation for stopping codes and its LinearOperator interface for the matrix products used by the solver.