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
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:
|
out_features
|
Feature and prediction widths.
TYPE:
|
bias
|
Fit an unpenalized intercept by centering the supervised rows.
TYPE:
|
name
|
Readout name for custom DAG training targets.
TYPE:
|
trainable
|
Allow gradient updates of fitted readout parameters after fitting.
TYPE:
|
alpha
|
Finite non-negative L2 penalty; never increased automatically.
TYPE:
|
atol
|
Finite non-negative SciPy backward-error stopping tolerances. These are relative tests, not the absolute residual cutoff used by CGReadoutLayer.
TYPE:
|
btol
|
Finite non-negative SciPy backward-error stopping tolerances. These are relative tests, not the absolute residual cutoff used by CGReadoutLayer.
TYPE:
|
conlim
|
Finite non-negative estimated condition limit. Zero disables this limit.
TYPE:
|
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:
|
chunk_size
|
Maximum rows centered in scratch storage during each operator product.
TYPE:
|
cpu_fallback
|
Permit the warned CPU float64 bridge for accelerator feature tensors.
TYPE:
|
| ATTRIBUTE | DESCRIPTION |
|---|---|
last_solve |
Diagnostics from the last successful solve. Reports are runtime metadata and are not preserved in portable checkpoints.
TYPE:
|
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 | |
solve
¶
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 | |
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.