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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338 | def lsmr(
*,
atol: float = 1e-6,
btol: float = 1e-6,
ctol: float = 1e-8,
maxiter: int = 1_000_000,
while_loop=control_flow.while_loop,
):
"""Construct an experimental implementation of LSMR.
Follows the [implementation in SciPy](https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.linalg.lsmr.html),
but uses JAX.
"""
# todo: stop iteration when NaN or Inf are detected.
@tree.register_dataclass
@containers.dataclass
class State:
"""LSMR state."""
# Iteration count:
itn: int
# Bidiagonalisation variables:
alpha: float
u: Array
v: Array
# LSMR-specific variables:
alphabar: float
rhobar: float
rho: float
zeta: float
sbar: float
cbar: float
zetabar: float
hbar: Array
h: Array
x: Array
# Variables for estimation of ||r||:
betadd: float
thetatilde: float
rhodold: float
betad: float
tautildeold: float
d: float
# Variables for estimation of ||A|| and cond(A)
normA2: float
maxrbar: float
minrbar: float
normA: float
condA: float
normx: float
# Variables for use in stopping rules
normar: float
normr: float
# Reason for stopping
istop: int
# more often than not, the matvec is defined after the LSMR
# solver has been constructed. So it's part of the run()
# function, not the LSMR constructor.
def run(vecmat, b, *vecmat_args, damp=0.0):
def vecmat_noargs(v):
return vecmat(v, *vecmat_args)
(ncols,) = func.eval_shape(vecmat, b, *vecmat_args).shape
state, normb, matvec_noargs = init(vecmat_noargs, b, ncols=ncols)
step_fun = make_step(matvec_noargs, normb=normb, damp=damp)
cond_fun = make_cond_fun()
state = while_loop(cond_fun, step_fun, state)
stats_ = stats(state)
return state.x, stats_
def init(vecmat, b, ncols: int):
normb = linalg.vector_norm(b)
x = np.zeros(ncols, dtype=b.dtype)
beta = normb
u = b
u = u / np.where(beta > 0, beta, 1.0)
v, matvec = func.vjp(vecmat, u)
alpha = linalg.vector_norm(v)
v = v / np.where(alpha > 0, alpha, 1)
v = np.where(beta == 0, np.zeros_like(v), v)
alpha = np.where(beta == 0, np.zeros_like(alpha), alpha)
# Initialize variables for 1st iteration.
zetabar = alpha * beta
alphabar = alpha
rho = 1.0
rhobar = 1.0
cbar = 1.0
sbar = 0.0
h = v
hbar = np.zeros(ncols, dtype=b.dtype)
# Initialize variables for estimation of ||r||.
betadd = beta
betad = 0.0
rhodold = 1.0
tautildeold = 0.0
thetatilde = 0.0
zeta = 0.0
d = 0.0
# Initialize variables for estimation of ||A|| and cond(A)
normA2 = alpha * alpha
maxrbar = 0.0
minrbar = 1e10
normA = np.sqrt(normA2)
condA = 1.0
normx = 0.0
# Items for use in stopping rules, normb set earlier
normr = beta
# Reverse the order here from the original matlab code because
# there was an error on return when arnorm==0
normar = alpha * beta
# Main iteration loop.
state = State( # type: ignore
itn=0,
alpha=alpha,
u=u,
v=v,
alphabar=alphabar,
rho=rho,
rhobar=rhobar,
zeta=zeta,
sbar=sbar,
cbar=cbar,
zetabar=zetabar,
hbar=hbar,
h=h,
x=x,
betadd=betadd,
thetatilde=thetatilde,
rhodold=rhodold,
betad=betad,
tautildeold=tautildeold,
d=d,
normA2=normA2,
maxrbar=maxrbar,
minrbar=minrbar,
normar=normar,
normr=normr,
normA=normA,
condA=condA,
normx=normx,
istop=0,
)
state = tree.tree_map(np.asarray, state)
return state, normb, lambda *a: matvec(*a)[0]
def make_step(matvec, normb: float, damp) -> Callable:
def step(state: State) -> State:
# Perform the next step of the bidiagonalization
Av, A_t = func.vjp(matvec, state.v)
u = Av - state.alpha * state.u
beta = linalg.vector_norm(u)
u = u / np.where(beta > 0, beta, 1.0)
v = A_t(u)[0] - beta * state.v
alpha = linalg.vector_norm(v)
v = v / np.where(alpha > 0, alpha, 1)
# Construct rotation Qhat_{k,2k+1}.
chat, shat, alphahat = _sym_ortho(state.alphabar, damp)
# Use a plane rotation (Q_i) to turn B_i to R_i
rhoold = state.rho
c, s, rho = _sym_ortho(alphahat, beta)
thetanew = s * alpha
alphabar = c * alpha
# Use a plane rotation (Qbar_i) to turn R_i^T to R_i^bar
rhobarold = state.rhobar
zetaold = state.zeta
thetabar = state.sbar * rho
rhotemp = state.cbar * rho
cbar, sbar, rhobar = _sym_ortho(rhotemp, thetanew)
zeta = cbar * state.zetabar
zetabar = -sbar * state.zetabar
# Update h, h_hat, x.
hbar = state.h - state.hbar * (thetabar * rho / (rhoold * rhobarold))
x = state.x + (zeta / (rho * rhobar)) * hbar
h = v - state.h * (thetanew / rho)
# Estimate of ||r||.
# Apply rotation Qhat_{k,2k+1}.
betaacute = chat * state.betadd
betacheck = -shat * state.betadd
# Apply rotation Q_{k,k+1}.
betahat = c * betaacute
betadd = -s * betaacute
# Apply rotation Qtilde_{k-1}.
thetatildeold = state.thetatilde
ctildeold, stildeold, rhotildeold = _sym_ortho(state.rhodold, thetabar)
thetatilde = stildeold * rhobar
rhodold = ctildeold * rhobar
betad = -stildeold * state.betad + ctildeold * betahat
tautildeold = (zetaold - thetatildeold * state.tautildeold) / rhotildeold
taud = (zeta - thetatilde * tautildeold) / rhodold
d = state.d + betacheck * betacheck
normr = np.sqrt(d + (betad - taud) ** 2 + betadd * betadd)
# Estimate ||A||.
normA2 = state.normA2 + beta * beta
normA = np.sqrt(normA2)
normA2 = normA2 + alpha * alpha
# Estimate cond(A).
maxrbar = np.elementwise_max(state.maxrbar, rhobarold)
minrbar = np.where(
state.itn > 1,
np.elementwise_min(state.minrbar, rhobarold),
state.minrbar,
)
condA = np.elementwise_max(maxrbar, rhotemp) / np.elementwise_min(
minrbar, rhotemp
)
# Compute norms for convergence testing.
normar = np.abs(zetabar)
normx = linalg.vector_norm(x)
# Check whether we should stop
itn = state.itn + 1
test1 = normr / normb
z = normA * normr
z_safe = np.where(z != 0, z, 1.0)
test2 = np.where(z != 0, normar / z_safe, _LARGE_VALUE)
test3 = 1 / condA
t1 = test1 / (1 + normA * normx / normb)
rtol = btol + atol * normA * normx / normb
# Early exits
istop = 0
istop = np.where(normar == 0, 9, istop)
istop = np.where(normb == 0, 8, istop)
istop = np.where(itn >= maxiter, 7, istop)
istop = np.where(1 + test3 <= 1, 6, istop)
istop = np.where(1 + test2 <= 1, 5, istop)
istop = np.where(1 + t1 <= 1, 4, istop)
istop = np.where(test3 <= ctol, 3, istop)
istop = np.where(test2 <= atol, 2, istop)
istop = np.where(test1 <= rtol, 1, istop)
return State( # type: ignore
itn=itn,
alpha=alpha,
u=u,
v=v,
alphabar=alphabar,
rho=rho,
rhobar=rhobar,
zeta=zeta,
sbar=sbar,
cbar=cbar,
zetabar=zetabar,
hbar=hbar,
h=h,
x=x,
betadd=betadd,
thetatilde=thetatilde,
rhodold=rhodold,
betad=betad,
tautildeold=tautildeold,
d=d,
normA2=normA2,
maxrbar=maxrbar,
minrbar=minrbar,
normar=normar,
normr=normr,
normA=normA,
condA=condA,
normx=normx,
istop=istop,
)
return step
def make_cond_fun() -> Callable:
def cond(state):
state_flat, _ = tree.ravel_pytree(state)
no_nans = np.logical_not(np.any(np.isnan(state_flat)))
proceed = np.where(state.istop == 0, True, False)
return np.logical_and(proceed, no_nans)
return cond
def stats(state: State) -> dict:
return {
"iteration_count": state.itn,
"norm_residual": state.normr,
"norm_At_residual": state.normar,
"norm_A": state.normA,
"cond_A": state.condA,
"norm_x": state.normx,
"istop": state.istop,
}
return run
|