Debian Codegraph @

packages/belos/tpetra/src/solvers/Belos_Tpetra_GmresPipeline.hpp

raw
1 // @HEADER
2 // *****************************************************************************
3 // Belos: Block Linear Solvers Package
4 //
5 // Copyright 2004-2016 NTESS and the Belos contributors.
6 // SPDX-License-Identifier: BSD-3-Clause
7 // *****************************************************************************
8 // @HEADER
9
10 #ifndef BELOS_TPETRA_GMRES_PIPELINE_HPP
11 #define BELOS_TPETRA_GMRES_PIPELINE_HPP
12
13 #include "Belos_Tpetra_Gmres.hpp"
14 #include "Belos_Tpetra_UpdateNewton.hpp"
15 #include "Tpetra_idot.hpp"
16
17 namespace BelosTpetra {
18 namespace Impl {
19
20 template<class SC = Tpetra::Operator<>::scalar_type,
21 class MV = Tpetra::MultiVector<SC>,
22 class OP = Tpetra::Operator<SC>>
23 class GmresPipeline : public Gmres<SC, MV, OP> {
24 private:
25 using base_type = Gmres<SC, MV, OP>;
26 using MVT = Belos::MultiVecTraits<SC, MV>;
27 using LO = typename MV::local_ordinal_type;
28 using STS = Teuchos::ScalarTraits<SC>;
29 using mag_type = typename STS::magnitudeType;
30 using STM = Teuchos::ScalarTraits<mag_type>;
31 using complex_type = std::complex<mag_type>;
32 using dense_matrix_type = Teuchos::SerialDenseMatrix<LO, SC>;
33 using dense_vector_type = Teuchos::SerialDenseVector<LO, SC>;
34 using vec_type = typename Krylov<SC, MV, OP>::vec_type;
35 using device_type = typename MV::device_type;
36 using dot_type = typename MV::dot_type;
37 using dot_view_type = Kokkos::View<dot_type*, device_type>;
38
39 public:
40 GmresPipeline () :
41 base_type::Gmres ()
42 {
43 this->input_.computeRitzValues = true;
44 }
45
46 GmresPipeline (const Teuchos::RCP<const OP>& A) :
47 base_type::Gmres (A)
48 {
49 this->input_.computeRitzValues = true;
50 }
51
52 virtual ~GmresPipeline () = default;
53
54 private:
55 SolverOutput<SC>
56 solveOneVec (Teuchos::FancyOStream* outPtr,
57 vec_type& X, // in X/out X
58 vec_type& B, // in B
59 const OP& A,
60 const OP& M,
61 const SolverInput<SC>& input)
62 {
63 using std::endl;
64
65 int restart = input.resCycle;
66 int ell = 1;
67 const SC zero = STS::zero ();
68 const SC one = STS::one ();
69 const mag_type eps = STS::eps ();
70 const mag_type tolOrtho = mag_type (10.0) * STM::squareroot (eps);
71 const bool computeRitzValues = input.computeRitzValues;
72
73 // timers
74 Teuchos::RCP< Teuchos::Time > spmvTimer = Teuchos::TimeMonitor::getNewCounter ("GmresPipeline::matrix-apply");
75
76 // initialize output parameters
77 SolverOutput<SC> output {};
78 output.converged = false;
79 output.numRests = 0;
80 output.numIters = 0;
81
82 Teuchos::BLAS<LO ,SC> blas;
83
84 mag_type b_norm; // initial residual norm
85 mag_type b0_norm; // initial residual norm, not left-preconditioned
86 mag_type r_norm;
87 mag_type r_norm_imp = -STM::one ();
88 dense_matrix_type G (restart+1, restart+1, true);
89 dense_matrix_type H (restart+1, restart, true);
90 dense_vector_type y (restart+1, true);
91 dense_vector_type h (restart+1, true);
92 std::vector<mag_type> cs (restart);
93 std::vector<SC> sn (restart);
94
95 bool zeroOut = false; // Kokkos::View:init can take a long time on GPU?
96 MV Q (B.getMap (), restart+1, zeroOut);
97 MV V (B.getMap (), restart+1, zeroOut);
98 vec_type R (B.getMap (), zeroOut);
99 vec_type Y (B.getMap (), zeroOut);
100 vec_type MZ (B.getMap (), zeroOut);
101 vec_type Z0 = * (V.getVectorNonConst (0));
102
103 // initial residual (making sure R = B - Ax)
104 {
105 Teuchos::TimeMonitor LocalTimer (*spmvTimer);
106 A.apply (X, R);
107 }
108 R.update (one, B, -one);
109 // TODO: this should be idot?
110 b0_norm = STM::squareroot (STS::real (R.dot (R))); // initial residual norm, no preconditioned
111 if (input.precoSide == "left") {
112 M.apply (R, Z0);
113 // TODO: this should be idot?
114 b_norm = STS::real (Z0.dot( Z0 )); //Z.norm2 (); // initial residual norm, preconditioned
115 }
116 else {
117 b_norm = b0_norm;
118 }
119 r_norm = b_norm;
120
121 if (computeRitzValues) {
122 // Invoke standard Gmres for the first restart cycle, to compute
123 // Ritz values as Newton shifts
124 SolverInput<SC> input_gmres = input;
125 input_gmres.maxNumIters = input.resCycle;
126 input_gmres.computeRitzValues = true;
127
128 Tpetra::deep_copy (R, B);
129 output = Gmres<SC, MV, OP>::solveOneVec (outPtr, X, R, A, M,
130 input_gmres);
131 if (output.converged) {
132 return output; // standard GMRES converged
133 }
134 if (input.precoSide == "left") {
135 M.apply (R, Z0);
136 r_norm = Z0.norm2 (); // residual norm
137 }
138 else {
139 r_norm = output.absResid;
140 }
141 output.numRests++;
142 }
143 if (input.precoSide != "left") {
144 Tpetra::deep_copy (Z0, R);
145 }
146
147 // for idot
148 std::shared_ptr<Tpetra::Details::CommRequest> req;
149 dot_view_type vals ("results[numVecs]", restart+1);
150 auto vals_h = Kokkos::create_mirror_view (vals);
151
152 // Initialize starting vector
153 //Z.scale (one / b_norm);
154 G(0, 0) = r_norm*r_norm;
155 y[0] = r_norm;
156
157 // Main loop
158 int iter = 0;
159 mag_type metric = 2*input.tol; // to make sure to hit the first synch
160 while (output.numIters < input.maxNumIters && ! output.converged) {
161 if (iter == 0) {
162 if (input.maxNumIters < output.numIters+restart) {
163 restart = input.maxNumIters-output.numIters;
164 }
165
166 // Normalize initial vector
167 MVT::MvScale (Z0, one/std::sqrt(G(0, 0)));
168
169 // Copy initial vector
170 vec_type AP = * (Q.getVectorNonConst (0));
171 Tpetra::deep_copy (AP, Z0);
172 }
173
174 // Restart cycle
175 for (; iter < restart+ell && metric > input.tol; ++iter) {
176 if (iter < restart) {
177 // W = A*Z
178 vec_type Z = * (V.getVectorNonConst (iter));
179 vec_type W = * (V.getVectorNonConst (iter+1));
180 if (input.precoSide == "none") {
181 Teuchos::TimeMonitor LocalTimer (*spmvTimer);
182 A.apply (Z, W);
183 }
184 else if (input.precoSide == "right") {
185 M.apply (Z, MZ);
186 {
187 Teuchos::TimeMonitor LocalTimer (*spmvTimer);
188 A.apply (MZ, W);
189 }
190 }
191 else {
192 {
193 Teuchos::TimeMonitor LocalTimer (*spmvTimer);
194 A.apply (Z, MZ);
195 }
196 M.apply (MZ, W);
197 }
198 // Shift for Newton basis, explicitly for the first iter
199 // (rest is done through change-of-basis)
200 if (computeRitzValues && iter == 0) {
201 //W.update (-output.ritzValues(iter%ell), Z, one);
202 const complex_type theta = output.ritzValues[iter%ell];
203 UpdateNewton<SC, MV>::updateNewtonV (iter, V, theta);
204 }
205 output.numIters ++;
206 }
207 int k = iter+1 - ell; // we synch idot from k-th iteration
208 if (outPtr != nullptr && k > 0) {
209 *outPtr << "Current pipeline iteration: iter=" << iter
210 << ", restart=" << restart
211 << ", metric=" << metric << endl;
212 Indent indent3 (outPtr);
213 }
214
215 // Compute G and H
216 if (k >= 0) {
217 if (k > 0) {
218 req->wait (); // wait for idot
219 auto v_iter = Kokkos::subview(vals, std::pair<int, int>(0, iter+1));
220 auto h_iter = Kokkos::subview(vals_h, std::pair<int, int>(0, iter+1));
221 Kokkos::deep_copy (h_iter, v_iter);
222
223 for (int i = 0; i <= iter; i++) {
224 G(i, k) = vals_h[i];
225 }
226 for (int i = 0; i <= k; ++i) {
227 H(i, k-1) = G(i, k);
228 }
229 // Integrate shift for Newton basis (applied through
230 // change-of-basis)
231 if (computeRitzValues) {
232 //H(k-1, k-1) += output.getRitzValue((k-1)%ell);
233 const complex_type theta = output.ritzValues[(k-1)%ell];
234 UpdateNewton<SC, MV>::updateNewtonH (k-1, H, theta);
235 }
236
237 // Fix H
238 for (int i = 0; i < k; ++i) {
239 H(k, k-1) -= (G(i, k)*G(i, k));
240 }
241 TEUCHOS_TEST_FOR_EXCEPTION
242 (STS::real (H(k, k-1)) < STM::zero (), std::runtime_error,
243 "At iteration " << iter << ", H(" << k << ", "
244 << k-1 << ") = " << H(k, k-1) << " < 0.");
245 H(k, k-1) = std::sqrt( H(k, k-1) );
246 }
247
248 if (k > 0) {
249 // Orthogonalize V(:, k), k = iter+1-ell
250 vec_type AP = * (Q.getVectorNonConst (k));
251 Teuchos::Range1D index_prev (0, k-1);
252 const MV Qprev = * (Q.subView (index_prev));
253 dense_matrix_type g_prev (Teuchos::View, G, k, 1, 0, k);
254
255 MVT::MvTimesMatAddMv (-one, Qprev, g_prev, one, AP);
256 MVT::MvScale (AP, one/H(k, k-1));
257 }
258 }
259
260 if (iter < restart) {
261 // Apply change-of-basis to W
262 vec_type W = * (V.getVectorNonConst (iter+1));
263 if (k > 0) {
264 Teuchos::Range1D index_prev (ell, iter);
265 const MV Zprev = * (V.subView (index_prev));
266
267 dense_matrix_type h_prev (Teuchos::View, H, k, 1, 0, k-1);
268 MVT::MvTimesMatAddMv (-one, Zprev, h_prev, one, W);
269
270 MVT::MvScale (W, one/H(k, k-1));
271 }
272 }
273
274 if (k > 0) {
275 TEUCHOS_TEST_FOR_EXCEPTION
276 (STS::real (H(k, k-1)) < STM::zero (), std::runtime_error,
277 "At iteration " << k << ", H(" << k << ", " << k-1 << ") = "
278 << H(k, k-1) << " < 0.");
279 // NOTE (mfh 16 Sep 2018) It's not entirely clear to me
280 // whether the code as given to me was correct for complex
281 // arithmetic. I'll do my best to make it compile.
282 if (STS::real (H(k, k-1)) > STS::real (tolOrtho*G(k, k))) {
283 // Apply Givens rotations to new column of H and y
284 this->reduceHessenburgToTriangular (k-1, H, cs, sn, y.values());
285 // Convergence check
286 metric = this->getConvergenceMetric (STS::magnitude (y(k)),
287 b_norm, input);
288 }
289 else { // breakdown
290 H(k, k-1) = zero;
291 metric = STM::zero ();
292 }
293 }
294
295 if (iter < restart && metric > input.tol) {
296 // Copy the new vector
297 vec_type AP = * (Q.getVectorNonConst (iter+1));
298 Tpetra::deep_copy (AP, * (V.getVectorNonConst (iter+1)));
299
300 // Start all-reduce to compute G(:, iter+1)
301 // [Q(:,1:k-1), V(:,k:iter+1)]'*W
302 Teuchos::Range1D index_prev(0, iter+1);
303 const MV Qprev = * (Q.subView(index_prev));
304
305 dot_view_type v_iter = Kokkos::subview(vals, std::pair<int, int>(0, iter+2));
306 vec_type W = * (V.getVectorNonConst (iter+1));
307 req = Tpetra::idot (v_iter, Qprev, static_cast<const MV&> (W));
308 }
309 } // End of restart cycle
310
311 if (iter < restart+ell) {
312 // save the old solution, just in case explicit residual norm failed the convergence test
313 Tpetra::deep_copy (Y, X);
314 blas.COPY (1+iter, y.values(), 1, h.values(), 1);
315 }
316 if (iter >= ell) {
317 r_norm_imp = STS::magnitude (y (iter - ell)); // save implicit residual norm
318
319 // Update solution
320 blas.TRSM (Teuchos::LEFT_SIDE, Teuchos::UPPER_TRI,
321 Teuchos::NO_TRANS, Teuchos::NON_UNIT_DIAG,
322 iter-ell, 1, one,
323 H.values(), H.stride(), y.values(), y.stride());
324 Teuchos::Range1D cols(0, (iter-ell)-1);
325 Teuchos::RCP<const MV> Qj = Q.subView(cols);
326 y.resize (iter);
327 if (input.precoSide == "right") {
328 dense_vector_type y_iter (Teuchos::View, y.values (), iter-ell);
329 MVT::MvTimesMatAddMv (one, *Qj, y_iter, zero, R);
330 M.apply (R, MZ);
331 X.update (one, MZ, one);
332 }
333 else {
334 dense_vector_type y_iter (Teuchos::View, y.values (), iter-ell);
335 MVT::MvTimesMatAddMv (one, *Qj, y_iter, one, X);
336 }
337 y.resize (restart+1);
338 }
339 // Compute real residual
340 {
341 Teuchos::TimeMonitor LocalTimer (*spmvTimer);
342 A.apply (X, R);
343 }
344 R.update (one, B, -one);
345 // TODO: compute residual norm with all-reduce, should be idot?
346 r_norm = R.norm2 ();
347 output.absResid = r_norm;
348 output.relResid = r_norm / b_norm;
349 if (outPtr != nullptr) {
350 *outPtr << "Implicit and explicit residual norms at restart: " << r_norm_imp << ", " << r_norm << endl;
351 }
352
353 // Convergence check (with explicitly computed residual norm)
354 metric = this->getConvergenceMetric (r_norm, b_norm, input);
355 if (metric <= input.tol) {
356 output.converged = true;
357 }
358 else if (output.numIters < input.maxNumIters) {
359 // Restart, only if max inner-iteration was reached.
360 // Otherwise continue the inner-iteration.
361 if (iter >= restart+ell) {
362 // Restart: Initialize starting vector for restart
363 iter = 0;
364 Z0 = * (V.getVectorNonConst (0));
365 if (input.precoSide == "left") {
366 M.apply (R, Z0);
367 r_norm = STS::real (Z0.dot (Z0)); //norm2 (); // residual norm
368 }
369 else {
370 // set the starting vector
371 Tpetra::deep_copy (Z0, R);
372 }
373 G(0, 0) = r_norm;
374 r_norm = STM::squareroot (r_norm);
375 //Z.scale (one / r_norm);
376 y[0] = r_norm;
377 for (int i=1; i < restart+1; ++i) {
378 y[i] = zero;
379 }
380 // Restart
381 output.numRests ++;
382 }
383 else {
384 // reset to the old solution
385 Tpetra::deep_copy (X, Y);
386 blas.COPY (1+iter, h.values(), 1, y.values(), 1);
387 {
388 // Copy the new vector
389 vec_type AP = * (Q.getVectorNonConst (iter));
390 Tpetra::deep_copy (AP, * (V.getVectorNonConst (iter)));
391
392 // Start all-reduce to compute G(:, iter)
393 // [Q(:,1:k-1), V(:,k:iter)]'*W
394 Teuchos::Range1D index_prev(0, iter);
395 const MV Qprev = * (Q.subView(index_prev));
396
397 vec_type W = * (V.getVectorNonConst (iter));
398 req = Tpetra::idot (vals, Qprev, static_cast<const MV&> (W));
399 }
400 }
401 }
402 }
403
404 return output;
405 }
406 };
407
408 template<class SC, class MV, class OP,
409 template<class, class, class> class KrylovSubclassType>
410 class SolverManager;
411
412 // This is the Belos::SolverManager subclass that gets registered with
413 // Belos::SolverFactory.
414 template<class SC, class MV, class OP>
415 using GmresPipelineSolverManager = SolverManager<SC, MV, OP, GmresPipeline>;
416
417 /// \brief Register GmresPipelineSolverManager for all enabled Tpetra
418 /// template parameter combinations.
419 void register_GmresPipeline (const bool verbose);
420
421 } // namespace Impl
422 } // namespace BelosTpetra
423
424 #endif // BELOS_TPETRA_GMRES_PIPELINE_HPP