flow 1.4.0
Kokkos cut-cell IBM incompressible Navier-Stokes solver + pnm pore extraction
Loading...
Searching...
No Matches
mac_cutcell_mg.hpp
Go to the documentation of this file.
1
14#ifndef PECLET_FLOW_MAC_CUTCELL_MG_HPP
15#define PECLET_FLOW_MAC_CUTCELL_MG_HPP
16
17#include <algorithm>
18#include <cassert>
19#include <chrono>
20#include <cmath>
21#include <cstdint>
22#include <cstdio>
23#include <cstdlib>
24#include <Kokkos_Core.hpp>
25#include <limits>
26#include <memory>
27#include <optional>
28#include <stdexcept>
29#include <string>
30#include <vector>
31
32#include "ghost_projection.hpp" // GpOverlay + gpApplyDelta (ghost-projection BiCGStab matvec)
33#include "mac_bc.hpp"
34#include "mac_pressure.hpp"
35#include "mg_bottom_direct.hpp" // §13: the direct preconditioner of the device bottom
36#include "peclet/core/solver/graph_amg.hpp" // decomposition-agnostic algebraic bottom solve
37#include "star_elimination.hpp" // StarOverlay + starApplyDelta (mode-B fluid-only PCG matvec)
38
39// Multi-rank (MPI) path is opt-in: the single-GPU module never links MPI, so all distributed code
40// is gated (mirrors the CUDA PECLET_FLOW_BUILD_MPI gating). When PECLET_FLOW_MPI is off, CutcellMG
41// is byte-identical to before.
42#ifdef PECLET_FLOW_MPI
43#include <memory>
44#include <optional>
45#include <stdexcept>
46
47#include "peclet/core/decomp/block_decomposer.hpp"
48#include "peclet/core/decomp/grid_redistribute.hpp"
49#include "peclet/core/decomp/redistribute_topology.hpp"
50#include "peclet/core/decomp/stage_comm.hpp"
51#include "peclet/core/decomp/stage_target.hpp"
52#include "peclet/core/halo/grid_halo.hpp"
53#include "peclet/core/halo/grid_halo_topology.hpp"
54#include "policy.hpp"
55#endif
56
57namespace peclet::flow {
58
59#ifdef PECLET_FLOW_MPI
60using peclet::core::halo::GridHalo;
61using peclet::core::halo::GridHaloTopology;
62#endif
63
64// Operator/level storage precision. Float (the CUDA-era default) breaks the singular row-sum
65// identity A*1=0 at ~eps_f relative per row; under high face-coefficient contrast (order-2
66// apertures span 3 decades) the defect on mixed large+tiny rows is amplified to ~eps_f*contrast,
67// which perturbs the near-null vector the mean-removal deflation assumes and floors/rebounds the
68// CG-family drivers near r/r0 ~ 1e-6 (see doc/collocated_paper_plan.md row 55). The bottom AMG
69// already re-sums its diagonal in double for exactly this reason. -DPECLET_FLOW_OPERATOR_DOUBLE
70// switches the whole hierarchy to double (A/B instrument; ~2x operator memory).
71//
72// EVERY store into an FPV/FV must go through MReal, or the switch is silently partial. WO-M found
73// three families of hard `(float)` casts that survived the templating and clamped their operator to
74// float even in a double build: `IbmSolver::buildAdvStencil` / `buildAdvStencilVar` (the implicit-
75// FOU momentum stencil), `IbmSolver::addDragDiagonal` (the CFD-DEM face drag — its symptom was a
76// porous steady drag balance stuck at 4.8e-8 in BOTH builds), and five sites in
77// `mac_velocity_mg.hpp` (the velocity-MG staircase / upwind-coarse / const-aniso operators and the
78// no-slip fold). They now cast to MReal, which is byte-identical when MReal is float.
79#ifdef PECLET_FLOW_OPERATOR_DOUBLE
80using MReal = double;
81#else
82using MReal = float; // operator storage = CUDA mreal
83#endif
84using FPV = Kokkos::View<MReal*, CCMem>;
85using FPC = Kokkos::View<const MReal*, CCMem>;
86// The FP32 V-cycle's storage and arithmetic type (doc/vof_projection_cost_design.md §4.4.2).
87using VReal = float; // PRECISION-EXEMPT: FP32 V-cycle preconditioner below the exact FP64 Krylov
88 // (doc/vof_projection_cost_design.md §4)
89
90// coarsen staggered face openness: each coarse face = average of the ratio_b*ratio_c fine sub-faces
91// it spans (mg_coarsen_open_avg_k port). gc/gf: coarse/fine block ghost widths (they can differ —
92// CA-eligible coarse levels carry g=2). The cell body is the A0 form (§5.2).
93template <class CV, class FV>
94KOKKOS_INLINE_FUNCTION void coarsenOpenAvgCell(const CV& oxc, const CV& oyc, const CV& ozc,
95 const FV& oxf, const FV& oyf, const FV& ozf, C3 cext,
96 C3 fext, int gc, int gf, C3 ratio, int icx, int icy,
97 int icz) {
98 const int rx = ratio.x, ry = ratio.y, rz = ratio.z;
99 const int fx0 = rx * icx + gf, fy0 = ry * icy + gf, fz0 = rz * icz + gf;
100 const long fsy = fext.x, fsz = (long)fext.x * fext.y;
101 auto F = [&](const FV& T, int x, int y, int z) {
102 return T((long)x + (long)y * fsy + (long)z * fsz);
103 };
104 double sx = 0, sy = 0, sz = 0;
105 for (int a = 0; a < ry; ++a)
106 for (int b = 0; b < rz; ++b)
107 sx += F(oxf, fx0, fy0 + a, fz0 + b);
108 for (int a = 0; a < rx; ++a)
109 for (int b = 0; b < rz; ++b)
110 sy += F(oyf, fx0 + a, fy0, fz0 + b);
111 for (int a = 0; a < rx; ++a)
112 for (int b = 0; b < ry; ++b)
113 sz += F(ozf, fx0 + a, fy0 + b, fz0);
114 const long ci =
115 (long)(icx + gc) + (long)(icy + gc) * cext.x + (long)(icz + gc) * (long)cext.x * cext.y;
116 oxc(ci) = sx / (double)(ry * rz);
117 oyc(ci) = sy / (double)(rx * rz);
118 ozc(ci) = sz / (double)(rx * ry);
119}
120inline void coarsenOpenAvg(CCField oxc, CCField oyc, CCField ozc, CCConst oxf, CCConst oyf,
121 CCConst ozf, C3 cext, C3 fext, int gc, int gf, C3 cinner, C3 ratio) {
122 ccFor3(
123 "peclet::flow::coarsen_open", C3{0, 0, 0}, C3{cinner.x, cinner.y, cinner.z},
124 KOKKOS_LAMBDA(int icx, int icy, int icz) {
125 coarsenOpenAvgCell(oxc, oyc, ozc, oxf, oyf, ozf, cext, fext, gc, gf, ratio, icx, icy, icz);
126 });
127}
128
129// --- WO-R2 item 1: the OUTFLOW face coefficient on a variable-density operator ----------------
130//
131// `applyBoundaryOpenness` used to re-impose the literal 1.0 at a Dirichlet (outflow) domain face on
132// EVERY level, which under `varRho` overwrote `buildRhoCoeff`'s `open_f * rho0/rho_f` with 1 and
133// made the operator row disagree with the projection correction by the full density ratio (WO-R's
134// headline defect: the Nusselt film's low-side outlet, `max|w|` 1.455 against a film `u_max` of
135// 0.312). The face index convention makes the two sides ASYMMETRIC:
136// * the LOW domain face of an axis is the INNER index `g` -> `buildRhoCoeff` (and, on a
137// coarse level, `coarsenOpenAvg`) already wrote the right value there; the fix is simply not
138// to overwrite it.
139// * the HIGH domain face is the GHOST index `dims-g` -> no kernel writes it, and the
140// periodic/halo ghost fill wraps the opposite boundary's value into it. It must be saved
141// before the fill and restored after (level 0, from the caller's field), and coarsened from
142// the fine level's own restored plane (coarse levels).
143// These three helpers do the save / restore / coarsen of ONE domain-face plane. They are only
144// reached when the caller sets `setOutflowCoefficient(true)` (the varRho pressure build); with it
145// off the literal-1.0 path is untouched and byte-identical.
146inline void mgSaveFacePlane(CCField dst, CCConst src, C3 e, int g, int a, int s) {
147 CCExec space;
148 int dims[3] = {e.x, e.y, e.z};
149 long st[3] = {1, (long)e.x, (long)e.x * e.y};
150 const int b = (a + 1) % 3, c = (a + 2) % 3;
151 const long sa = st[a], sb = st[b], sc = st[c];
152 const int bf = (s == 0) ? g : (dims[a] - g);
153 const int db = dims[b];
154 using MD = MDRange2<CCExec>;
155 Kokkos::parallel_for(
156 "peclet::flow::mg_save_face_plane", MD(space, {0, 0}, {dims[b], dims[c]}),
157 KOKKOS_LAMBDA(int p0, int p1) {
158 dst((long)p0 + (long)p1 * db) = src((long)p0 * sb + (long)p1 * sc + (long)bf * sa);
159 });
160}
161inline void mgRestoreFacePlane(CCField dst, CCConst src, C3 e, int g, int a, int s) {
162 CCExec space;
163 int dims[3] = {e.x, e.y, e.z};
164 long st[3] = {1, (long)e.x, (long)e.x * e.y};
165 const int b = (a + 1) % 3, c = (a + 2) % 3;
166 const long sa = st[a], sb = st[b], sc = st[c];
167 const int bf = (s == 0) ? g : (dims[a] - g);
168 const int db = dims[b];
169 using MD = MDRange2<CCExec>;
170 Kokkos::parallel_for(
171 "peclet::flow::mg_restore_face_plane", MD(space, {0, 0}, {dims[b], dims[c]}),
172 KOKKOS_LAMBDA(int p0, int p1) {
173 dst((long)p0 * sb + (long)p1 * sc + (long)bf * sa) = src((long)p0 + (long)p1 * db);
174 });
175}
176// Coarse domain-face plane = the area average of the ratio_b*ratio_c fine sub-faces it spans —
177// the same rule `coarsenOpenAvg` applies to every interior face, restricted to the one plane the
178// coarsening loop cannot reach (the high side lives on a ghost index). The coarse plane's own
179// TRANSVERSE ghost ring is filled by clamping the fine transverse index into range: it is read
180// only by the redundant ring rows of a distributed CA (g=2) level's smoother, and it is exact
181// whenever the coefficient is constant along the outlet (every constant-density case, and every
182// ratio-1 case, so the byte-identity and MPI gates are unaffected).
183inline void mgCoarsenFacePlane(CCField oc, CCConst of, C3 cext, C3 fext, int gc, int gf, C3 cinner,
184 C3 ratio, int a, int s) {
185 CCExec space;
186 int cd[3] = {cext.x, cext.y, cext.z}, fd[3] = {fext.x, fext.y, fext.z};
187 int ci[3] = {cinner.x, cinner.y, cinner.z}, rt[3] = {ratio.x, ratio.y, ratio.z};
188 long cst[3] = {1, (long)cext.x, (long)cext.x * cext.y};
189 long fst[3] = {1, (long)fext.x, (long)fext.x * fext.y};
190 const int b = (a + 1) % 3, c = (a + 2) % 3;
191 const long csa = cst[a], csb = cst[b], csc = cst[c];
192 const long fsa = fst[a], fsb = fst[b], fsc = fst[c];
193 const int cbf = (s == 0) ? gc : (cd[a] - gc);
194 const int fbf = (s == 0) ? gf : (fd[a] - gf);
195 const int rb = rt[b], rc = rt[c];
196 const int fdb = fd[b], fdc = fd[c];
197 const double inv = 1.0 / (double)(rb * rc);
198 using MD = MDRange2<CCExec>;
199 Kokkos::parallel_for(
200 "peclet::flow::mg_coarsen_face_plane", MD(space, {0, 0}, {cd[b], cd[c]}),
201 KOKKOS_LAMBDA(int p0, int p1) {
202 const int ib = p0 - gc, ic = p1 - gc; // coarse INNER indices (negative in the ghost ring)
203 double sum = 0.0;
204 for (int q0 = 0; q0 < rb; ++q0)
205 for (int q1 = 0; q1 < rc; ++q1) {
206 int fb = rb * ib + gf + q0, fc = rc * ic + gf + q1;
207 fb = fb < 0 ? 0 : (fb >= fdb ? fdb - 1 : fb);
208 fc = fc < 0 ? 0 : (fc >= fdc ? fdc - 1 : fc);
209 sum += of((long)fb * fsb + (long)fc * fsc + (long)fbf * fsa);
210 }
211 oc((long)p0 * csb + (long)p1 * csc + (long)cbf * csa) = sum * inv;
212 });
213 (void)ci;
214}
215
216// residual r = b - A x for the float operator (mg_residual_var_k port). A0 cell body (§5.2).
217template <class RV, class XV, class BV, class OpV>
218KOKKOS_INLINE_FUNCTION void cutcellResidualCell(const RV& r, const XV& x, const BV& b,
219 const OpV& AC, const OpV& AW, const OpV& AE,
220 const OpV& AS, const OpV& AN, const OpV& AB,
221 const OpV& AT, long i, long xp, long xm, long yp,
222 long ym, long zp, long zm) {
223 const double Ax = (double)AC(i) * x(i) + (double)AE(i) * x(xp) + (double)AW(i) * x(xm) +
224 (double)AN(i) * x(yp) + (double)AS(i) * x(ym) + (double)AT(i) * x(zp) +
225 (double)AB(i) * x(zm);
226 r(i) = b(i) - Ax;
227}
228inline void residualCutcell(CCField r, CCConst x, CCConst b, FPC AC, FPC AW, FPC AE, FPC AS, FPC AN,
229 FPC AB, FPC AT, C3 e, int g) {
230 ccFor3(
231 "peclet::flow::cc_residual", C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g},
232 KOKKOS_LAMBDA(int lx, int ly, int lz) {
233 const long sx = 1, sy = e.x, sz = (long)e.x * e.y;
234 const long i = (long)lx + (long)ly * sy + (long)lz * sz;
235 cutcellResidualCell(r, x, b, AC, AW, AE, AS, AN, AB, AT, i, i + sx, i - sx, i + sy, i - sy,
236 i + sz, i - sz);
237 });
238}
239
240// Residual over a box [rlo,rhi) minus a skip box [slo,shi) — the halo-overlapped form of
241// residualCutcell (interior first while the exchange is in flight, then the boundary shell).
242inline void residualCutcellBox(CCField r, CCConst x, CCConst b, FPC AC, FPC AW, FPC AE, FPC AS,
243 FPC AN, FPC AB, FPC AT, C3 e, C3 rlo, C3 rhi, C3 slo, C3 shi) {
244 if (rhi.x <= rlo.x || rhi.y <= rlo.y || rhi.z <= rlo.z)
245 return;
246 ccFor3(
247 "peclet::flow::cc_residual_box", rlo, rhi, KOKKOS_LAMBDA(int lx, int ly, int lz) {
248 if (lx >= slo.x && lx < shi.x && ly >= slo.y && ly < shi.y && lz >= slo.z && lz < shi.z)
249 return; // inside the skip box (already done by the interior pass)
250 const long sx = 1, sy = e.x, sz = (long)e.x * e.y;
251 const long i = (long)lx + (long)ly * sy + (long)lz * sz;
252 cutcellResidualCell(r, x, b, AC, AW, AE, AS, AN, AB, AT, i, i + sx, i - sx, i + sy, i - sy,
253 i + sz, i - sz);
254 });
255}
256
257// Face-form siblings of residualCutcell / residualCutcellBox (A2, see mac_pressure.hpp).
258inline void residualCutcellFace(CCField r, CCConst x, CCConst b, FPC AC, FPC AFX, FPC AFY, FPC AFZ,
259 C3 e, int g) {
260 ccFor3(
261 "peclet::flow::cc_residual", C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g},
262 KOKKOS_LAMBDA(int lx, int ly, int lz) {
263 const long sx = 1, sy = e.x, sz = (long)e.x * e.y;
264 const long i = (long)lx + (long)ly * sy + (long)lz * sz;
265 cutcellResidualFaceCell(r, x, b, AC, AFX, AFY, AFZ, i, sx, sy, sz, i + sx, i - sx, i + sy,
266 i - sy, i + sz, i - sz);
267 });
268}
269inline void residualCutcellBoxFace(CCField r, CCConst x, CCConst b, FPC AC, FPC AFX, FPC AFY,
270 FPC AFZ, C3 e, C3 rlo, C3 rhi, C3 slo, C3 shi, int wrapMask = 0,
271 int g = 1) {
272 if (rhi.x <= rlo.x || rhi.y <= rlo.y || rhi.z <= rlo.z)
273 return;
274 if (wrapMask != 0) { // K3 (doc/vof_distributed_host_comm_design.md §5.2): in-kernel wrap reads
275 const C3 n{e.x - 2 * g, e.y - 2 * g, e.z - 2 * g};
276 if constexpr (std::is_same_v<typename CCExec::memory_space, Kokkos::HostSpace>) {
277 auto run = [=](int ly, int lz, int x0, int x1) {
278 const long sx = 1, sy = e.x, sz = (long)e.x * e.y;
279 ccMaskRow(ly, lz, x0, x1, 1, e, n, g, wrapMask,
280 [&](long i, long xp, long xm, long yp, long ym, long zp, long zm) {
281 cutcellResidualFaceCell(r, x, b, AC, AFX, AFY, AFZ, i, sx, sy, sz, xp, xm, yp,
282 ym, zp, zm);
283 });
284 };
285 ccBoxShellRuns("peclet::flow::cc_residual_box", rlo, rhi, slo, shi, run);
286 return;
287 }
288 ccFor3(
289 "peclet::flow::cc_residual_box", rlo, rhi, KOKKOS_LAMBDA(int lx, int ly, int lz) {
290 if (lx >= slo.x && lx < shi.x && ly >= slo.y && ly < shi.y && lz >= slo.z && lz < shi.z)
291 return;
292 const long sx = 1, sy = e.x, sz = (long)e.x * e.y;
293 const long i = (long)lx + (long)ly * sy + (long)lz * sz;
294 const CcNbrs w = ccMaskNbrs(lx, ly, lz, n, g, i, sy, sz, wrapMask);
295 cutcellResidualFaceCell(r, x, b, AC, AFX, AFY, AFZ, i, sx, sy, sz, w.xp, w.xm, w.yp, w.ym,
296 w.zp, w.zm);
297 });
298 return;
299 }
300 if constexpr (std::is_same_v<typename CCExec::memory_space, Kokkos::HostSpace>) {
301 // H-7 (doc/vof_step_performance_design.md §14.3): shell-only shell launch, skip-test-free
302 // interior launch (ccBoxShellRuns). Same cells, same body.
303 auto run = [=](int ly, int lz, int x0, int x1) {
304 const long sx = 1, sy = e.x, sz = (long)e.x * e.y;
306 for (int lx = x0; lx < x1; ++lx) {
307 const long i = (long)lx + (long)ly * sy + (long)lz * sz;
308 cutcellResidualFaceCell(r, x, b, AC, AFX, AFY, AFZ, i, sx, sy, sz, i + sx, i - sx, i + sy,
309 i - sy, i + sz, i - sz);
310 }
311 };
312 ccBoxShellRuns("peclet::flow::cc_residual_box", rlo, rhi, slo, shi, run);
313 return;
314 }
315 ccFor3(
316 "peclet::flow::cc_residual_box", rlo, rhi, KOKKOS_LAMBDA(int lx, int ly, int lz) {
317 if (lx >= slo.x && lx < shi.x && ly >= slo.y && ly < shi.y && lz >= slo.z && lz < shi.z)
318 return; // inside the skip box (already done by the interior pass)
319 const long sx = 1, sy = e.x, sz = (long)e.x * e.y;
320 const long i = (long)lx + (long)ly * sy + (long)lz * sz;
321 cutcellResidualFaceCell(r, x, b, AC, AFX, AFY, AFZ, i, sx, sy, sz, i + sx, i - sx, i + sy,
322 i - sy, i + sz, i - sz);
323 });
324}
325
326// --- A3: fused periodic wrap (doc/vof_step_performance_design.md §4.3, §5.4) -------------------
327// On a single-rank level whose ghosts a periodic fill would only COPY from the inner cells (no
328// outflow face, no overlay on the solve), the smoother, the residual and the Krylov matvec read a
329// boundary cell's periodic neighbour directly through the wrapped index instead of from a ghost
330// filled by a launch before each pass: per axis a, for inner coordinate k in [g, g+n_a),
331// minus neighbour = (k == g) ? i + (n_a-1) s_a : i - s_a
332// plus neighbour = (k == g+n_a-1) ? i - (n_a-1) s_a : i + s_a.
333// That is the very cell the fill copies into the ghost, so a read-only pass (residual, matvec)
334// reads the identical value. A red-black colour pass does too exactly when every inner dimension is
335// EVEN: the wrapped neighbour then has the other colour, which this pass does not update, so it
336// still holds the value the fill copied before the pass (the caller checks the parity). Only the
337// field being smoothed or applied is wrapped; the coefficients are static over a solve and are read
338// at their ghost indices as before (AFX(i+sx) at the high ghost holds the periodic face, and a wall
339// face's coefficient is 0 there, multiplying the wrapped value exactly as it multiplied the ghost).
340// (CcNbrs lives in mac_cutcell.hpp, beside K3's per-axis ccMaskNbrs.)
341KOKKOS_INLINE_FUNCTION CcNbrs ccWrapNbrs(int lx, int ly, int lz, C3 n, int g, long i, long sy,
342 long sz) {
343 CcNbrs w;
344 w.xm = (lx == g) ? i + (long)(n.x - 1) : i - 1;
345 w.xp = (lx == g + n.x - 1) ? i - (long)(n.x - 1) : i + 1;
346 w.ym = (ly == g) ? i + (long)(n.y - 1) * sy : i - sy;
347 w.yp = (ly == g + n.y - 1) ? i - (long)(n.y - 1) * sy : i + sy;
348 w.zm = (lz == g) ? i + (long)(n.z - 1) * sz : i - sz;
349 w.zp = (lz == g + n.z - 1) ? i - (long)(n.z - 1) * sz : i + sz;
350 return w;
351}
352// S (doc/vof_projection_cost_design.md §9, WO-S): the host row of an A3 wrap kernel with the row
353// ends PEELED. Per row the y/z neighbour offsets once (ccWrapNbrs' selects, loop-invariant in a
354// row); the first and last cell of the row take ccWrapNbrs (today's body); the interior reads
355// i +- 1, so the x-neighbour loads are affine instead of gathers. Same cells, same body, same
356// operands: bitwise to the ccWrapNbrs form. `cell(i, xp, xm, yp, ym, zp, zm)` is called for the
357// cells lx = lx0, lx0 + step, ... <= g + n.x - 1 of the row (step 2: one colour of the smoother).
358template <class Cell>
359KOKKOS_INLINE_FUNCTION void ccWrapRowPeeled(int ly, int lz, C3 e, C3 n, int g, int lx0, int step,
360 const Cell& cell) {
361 const long sy = e.x, sz = (long)e.x * e.y;
362 const long base = (long)ly * sy + (long)lz * sz;
363 const long dym = (ly == g) ? (long)(n.y - 1) * sy : -sy;
364 const long dyp = (ly == g + n.y - 1) ? -(long)(n.y - 1) * sy : sy;
365 const long dzm = (lz == g) ? (long)(n.z - 1) * sz : -sz;
366 const long dzp = (lz == g + n.z - 1) ? -(long)(n.z - 1) * sz : sz;
367 const int lxLast = g + n.x - 1;
368 if (lx0 > lxLast)
369 return;
370 const int last = lx0 + ((lxLast - lx0) / step) * step; // the row's last cell of the pass
371 auto scalar = [&](int lx) {
372 const long i = (long)lx + base;
373 const CcNbrs w = ccWrapNbrs(lx, ly, lz, n, g, i, sy, sz);
374 cell(i, w.xp, w.xm, w.yp, w.ym, w.zp, w.zm);
375 };
376 int lo = lx0, hi = last; // inclusive
377 if (lo == g) {
378 scalar(lo);
379 lo += step;
380 }
381 const bool peelLast = hi == lxLast && hi >= lo;
382 if (peelLast)
383 hi -= step;
384 PECLET_FLOW_OMP_SIMD // same as the unpeeled loop: independent cells
385 for (int lx = lo; lx <= hi; lx += step) {
386 const long i = (long)lx + base;
387 cell(i, i + 1, i - 1, i + dyp, i + dym, i + dzp, i + dzm);
388 }
389 if (peelLast)
390 scalar(lxLast);
391}
392// Every inner cell of a wrap kernel on a host backend, row-peeled (ccFor3's host structure: the
393// (y, z) row partition, the serial cutoff).
394template <class Cell>
395inline void ccWrapForPeeled(const char* name, C3 e, C3 n, int g, const Cell& cell) {
396 CCExec space;
397 const int nyi = e.y - 2 * g, nzi = e.z - 2 * g;
398 const long rows = (long)nyi * nzi;
399 auto row = [=](long t) {
400 ccWrapRowPeeled(g + (int)(t % nyi), g + (int)(t / nyi), e, n, g, g, 1, cell);
401 };
402 if (hostRunSerial(rows * (e.x - 2 * g))) {
403 const HostSerialRegion serialRegion(name, "@serial"); // WO-T
404 for (long t = 0; t < rows; ++t)
405 row(t);
406 return;
407 }
408 Kokkos::parallel_for(name, Kokkos::RangePolicy<CCExec>(space, 0, rows), row);
409}
410// cutcellSmoothColorFace with wrapped neighbour reads (n = the level's inner dims, all even).
411inline void cutcellSmoothColorFaceWrap(CCField phi, CCConst b, FPC AC, FPC AFX, FPC AFY, FPC AFZ,
412 C3 e, C3 n, C3 og, int g, int color) {
413 CCExec space;
414 if constexpr (std::is_same_v<typename CCExec::memory_space, Kokkos::HostSpace>) {
415 const int nyi = e.y - 2 * g, nzi = e.z - 2 * g;
416 const long cells = (long)nyi * nzi * (e.x - 2 * g);
417 auto pencil = KOKKOS_LAMBDA(long t) {
418 const int ly = g + (int)(t % nyi), lz = g + (int)(t / nyi);
419 const long sx = 1, sy = e.x, sz = (long)e.x * e.y;
420 const int P = (color + og.x + og.y + ly + og.z + lz) & 1;
421 // S: the row ends peeled (same-colour cells are independent: ccFor3's contract)
422 ccWrapRowPeeled(ly, lz, e, n, g, g + ((P ^ (g & 1)) & 1), 2,
423 [&](long i, long xp, long xm, long yp, long ym, long zp, long zm) {
424 cutcellSmoothFaceCell(phi, b, AC, AFX, AFY, AFZ, i, sx, sy, sz, xp, xm, yp,
425 ym, zp, zm);
426 });
427 };
428 if (hostRunSerial(cells)) { // coarse MG level: the fork/join costs more than the sweep
429 const HostSerialRegion serialRegion("peclet::flow::cc_smooth@serial"); // WO-T
430 for (long t = 0; t < (long)nyi * nzi; ++t)
431 pencil(t);
432 return;
433 }
434 Kokkos::parallel_for("peclet::flow::cc_smooth",
435 Kokkos::RangePolicy<CCExec>(space, 0, (long)nyi * nzi), pencil);
436 return;
437 }
438 using MD = MDRange3<CCExec>;
439 Kokkos::parallel_for(
440 "peclet::flow::cc_smooth", MD(space, {g, g, g}, {e.x - g, e.y - g, e.z - g}),
441 KOKKOS_LAMBDA(int lx, int ly, int lz) {
442 if (((og.x + lx + og.y + ly + og.z + lz) & 1) != color)
443 return;
444 const long sx = 1, sy = e.x, sz = (long)e.x * e.y;
445 const long i = (long)lx + (long)ly * sy + (long)lz * sz;
446 const CcNbrs w = ccWrapNbrs(lx, ly, lz, n, g, i, sy, sz);
447 cutcellSmoothFaceCell(phi, b, AC, AFX, AFY, AFZ, i, sx, sy, sz, w.xp, w.xm, w.yp, w.ym,
448 w.zp, w.zm);
449 });
450}
451// residualCutcellFace with wrapped reads of x.
453 FPC AFZ, C3 e, C3 n, int g) {
454 if constexpr (std::is_same_v<typename CCExec::memory_space, Kokkos::HostSpace>) { // S
455 const long sx = 1, sy = e.x, sz = (long)e.x * e.y;
456 ccWrapForPeeled("peclet::flow::cc_residual", e, n, g,
457 [=](long i, long xp, long xm, long yp, long ym, long zp, long zm) {
458 cutcellResidualFaceCell(r, x, b, AC, AFX, AFY, AFZ, i, sx, sy, sz, xp, xm, yp,
459 ym, zp, zm);
460 });
461 return;
462 }
463 ccFor3(
464 "peclet::flow::cc_residual", C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g},
465 KOKKOS_LAMBDA(int lx, int ly, int lz) {
466 const long sx = 1, sy = e.x, sz = (long)e.x * e.y;
467 const long i = (long)lx + (long)ly * sy + (long)lz * sz;
468 const CcNbrs w = ccWrapNbrs(lx, ly, lz, n, g, i, sy, sz);
469 cutcellResidualFaceCell(r, x, b, AC, AFX, AFY, AFZ, i, sx, sy, sz, w.xp, w.xm, w.yp, w.ym,
470 w.zp, w.zm);
471 });
472}
473// applyCutcellOpFace / applyCutcellOpExact with wrapped reads of x (the level-0 Krylov matvec).
474inline void applyCutcellOpFaceWrap(CCField y, CCConst x, FPC AC, FPC AFX, FPC AFY, FPC AFZ, C3 e,
475 C3 n, int g) {
476 ccFor3(
477 "peclet::flow::cc_apply", C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g},
478 KOKKOS_LAMBDA(int lx, int ly, int lz) {
479 const long sx = 1, sy = e.x, sz = (long)e.x * e.y;
480 const long i = (long)lx + (long)ly * sy + (long)lz * sz;
481 const CcNbrs w = ccWrapNbrs(lx, ly, lz, n, g, i, sy, sz);
482 y(i) = cutcellApplyFaceCell(x, AC, AFX, AFY, AFZ, i, sx, sy, sz, w.xp, w.xm, w.yp, w.ym,
483 w.zp, w.zm);
484 });
485}
487 C3 n, int g, double gfx, double gfy, double gfz) {
488 if constexpr (std::is_same_v<typename CCExec::memory_space, Kokkos::HostSpace>) { // S
489 const long sx = 1, sy = e.x, sz = (long)e.x * e.y;
490 ccWrapForPeeled("peclet::flow::cc_apply_exact", e, n, g,
491 [=](long i, long xp, long xm, long yp, long ym, long zp, long zm) {
492 y(i) = cutcellApplyExactCell(x, ox, oy, oz, i, sx, sy, sz, xp, xm, yp, ym, zp,
493 zm, gfx, gfy, gfz);
494 });
495 return;
496 }
497 ccFor3(
498 "peclet::flow::cc_apply_exact", C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g},
499 KOKKOS_LAMBDA(int lx, int ly, int lz) {
500 const long sx = 1, sy = e.x, sz = (long)e.x * e.y;
501 const long i = (long)lx + (long)ly * sy + (long)lz * sz;
502 const CcNbrs w = ccWrapNbrs(lx, ly, lz, n, g, i, sy, sz);
503 y(i) = cutcellApplyExactCell(x, ox, oy, oz, i, sx, sy, sz, w.xp, w.xm, w.yp, w.ym, w.zp,
504 w.zm, gfx, gfy, gfz);
505 });
506}
507
508// average restriction (coarse = mean of ratio^3 fine children; mg_restrict_k) + trilinear
509// prolongation (added to fine; mg_prolong_k). Both over inner cells. gc/gf: coarse/fine block
510// ghost widths (CA-eligible coarse levels carry g=2, so they can differ across one transfer).
511// A0 cell bodies (§5.2).
512template <class CV, class FV>
513KOKKOS_INLINE_FUNCTION void restrictAvgCell(const CV& coarse, const FV& fine, C3 cext, C3 fext,
514 int gc, int gf, C3 ratio, int icx, int icy, int icz) {
515 const long fsy = fext.x, fsz = (long)fext.x * fext.y;
516 double s = 0;
517 for (int dz = 0; dz < ratio.z; ++dz)
518 for (int dy = 0; dy < ratio.y; ++dy)
519 for (int dx = 0; dx < ratio.x; ++dx) {
520 const int fx = ratio.x * icx + dx + gf, fy = ratio.y * icy + dy + gf,
521 fz = ratio.z * icz + dz + gf;
522 s += fine((long)fx + (long)fy * fsy + (long)fz * fsz);
523 }
524 const long ci =
525 (long)(icx + gc) + (long)(icy + gc) * cext.x + (long)(icz + gc) * (long)cext.x * cext.y;
526 coarse(ci) = s / (double)(ratio.x * ratio.y * ratio.z);
527}
528template <class FV, class CV>
529KOKKOS_INLINE_FUNCTION void prolongAddCell(const FV& fine, const CV& coarse, C3 fext, C3 cext,
530 int gf, int gc, C3 ratio, int ifx, int ify, int ifz) {
531 // The coarse sample coordinate is 0.5*ifine - 0.25 + gc on a coarsened axis (ratio 2) and
532 // ifine + gc on a kept one (ratio 1); its floor is the lower coarse index and its fraction the
533 // weight. §14 H-2: both in integer arithmetic. The coordinate is exact in double, so its floor
534 // and fraction are exactly
535 // ratio 2: x0 = (i >> 1) + gc - 1 + (i & 1), w = 0.25 (i odd) or 0.75 (i even);
536 // ratio 1: x0 = i + gc, w = 0,
537 // and the interpolation below (textually unchanged) sees the same operands -- bit-identical,
538 // without three floors and six FP <-> int conversions per fine cell.
539 const int x0 = (ratio.x == 2) ? (ifx >> 1) + gc - 1 + (ifx & 1) : ifx + gc;
540 const int y0 = (ratio.y == 2) ? (ify >> 1) + gc - 1 + (ify & 1) : ify + gc;
541 const int z0 = (ratio.z == 2) ? (ifz >> 1) + gc - 1 + (ifz & 1) : ifz + gc;
542 const double wx = (ratio.x == 2) ? ((ifx & 1) ? 0.25 : 0.75) : 0.0;
543 const double wy = (ratio.y == 2) ? ((ify & 1) ? 0.25 : 0.75) : 0.0;
544 const double wz = (ratio.z == 2) ? ((ifz & 1) ? 0.25 : 0.75) : 0.0;
545 const long sy = cext.x, sz = (long)cext.x * cext.y;
546 auto C = [&](int xx, int yy, int zz) { return coarse((long)xx + (long)yy * sy + (long)zz * sz); };
547 const double c00 = C(x0, y0, z0) * (1 - wx) + C(x0 + 1, y0, z0) * wx;
548 const double c10 = C(x0, y0 + 1, z0) * (1 - wx) + C(x0 + 1, y0 + 1, z0) * wx;
549 const double c01 = C(x0, y0, z0 + 1) * (1 - wx) + C(x0 + 1, y0, z0 + 1) * wx;
550 const double c11 = C(x0, y0 + 1, z0 + 1) * (1 - wx) + C(x0 + 1, y0 + 1, z0 + 1) * wx;
551 const double c0 = c00 * (1 - wy) + c10 * wy, c1 = c01 * (1 - wy) + c11 * wy;
552 const long fi =
553 (long)(ifx + gf) + (long)(ify + gf) * fext.x + (long)(ifz + gf) * (long)fext.x * fext.y;
554 fine(fi) += c0 * (1 - wz) + c1 * wz;
555}
556// doc/mg_depth_policy.md A3.3 item 1: the piecewise-constant prolongation P = (prod ratio) R^T of
557// the average restriction (added to fine) -- every fine inner cell adds its coarse parent's value,
558// parent index i >> 1 on a ratio-2 axis, i on a kept one. Reads no coarse ghost.
559template <class FV, class CV>
560KOKKOS_INLINE_FUNCTION void prolongConstAddCell(const FV& fine, const CV& coarse, C3 fext, C3 cext,
561 int gf, int gc, C3 ratio, int ifx, int ify,
562 int ifz) {
563 const int cx = ((ratio.x == 2) ? (ifx >> 1) : ifx) + gc;
564 const int cy = ((ratio.y == 2) ? (ify >> 1) : ify) + gc;
565 const int cz = ((ratio.z == 2) ? (ifz >> 1) : ifz) + gc;
566 const long ci = (long)cx + (long)cy * cext.x + (long)cz * (long)cext.x * cext.y;
567 const long fi =
568 (long)(ifx + gf) + (long)(ify + gf) * fext.x + (long)(ifz + gf) * (long)fext.x * fext.y;
569 fine(fi) += coarse(ci);
570}
571// The subtract half of CutcellMG::removeMean (A0 cell body).
572template <class FV, class AV>
573KOKKOS_INLINE_FUNCTION void meanSubtractCell(const FV& f, const AV& ac, long i, double mean) {
574 if (ac(i) > 1e-30f)
575 f(i) -= mean;
576}
577inline void restrictAvg(CCField coarse, CCConst fine, C3 cext, C3 fext, int gc, int gf, C3 cinner,
578 C3 ratio) {
579 ccFor3(
580 "peclet::flow::restrict", C3{0, 0, 0}, C3{cinner.x, cinner.y, cinner.z},
581 KOKKOS_LAMBDA(int icx, int icy, int icz) {
582 restrictAvgCell(coarse, fine, cext, fext, gc, gf, ratio, icx, icy, icz);
583 });
584}
585// A5 (doc/vof_step_performance_design.md §5.5): restrictAvg that also zeroes the coarse ITERATE on
586// the same inner cells in the same kernel, replacing the full-array zero fill of `cs.x` the V-cycle
587// launched after the restriction. The coarse ghosts are no longer zeroed; every consumer fills,
588// wrap-reads or overwrites them first (the smoother and the residual fill or wrap before reading,
589// GraphAMG writes the whole array). VelocityMG keeps the plain restrictAvg.
590inline void restrictAvgZeroX(CCField coarse, CCField coarseX, CCConst fine, C3 cext, C3 fext,
591 int gc, int gf, C3 cinner, C3 ratio) {
592 ccFor3(
593 "peclet::flow::restrict", C3{0, 0, 0}, C3{cinner.x, cinner.y, cinner.z},
594 KOKKOS_LAMBDA(int icx, int icy, int icz) {
595 restrictAvgCell(coarse, fine, cext, fext, gc, gf, ratio, icx, icy, icz);
596 coarseX((long)(icx + gc) + (long)(icy + gc) * cext.x +
597 (long)(icz + gc) * (long)cext.x * cext.y) = 0.0;
598 });
599}
600// D (doc/vof_projection_cost_design.md §4.4.2): the FP32 V-cycle's face weights
601// WX = fl32(t_x), t_x = ox * gfx (POSITIVE; likewise y, z) over [0, ext), from the operands of
602// cutcellBuildFaceOpCell. `fp64` selects what the same kernel also writes of the FP64 operator:
603// kOpFp64Full = the face form with that cell body, unchanged (setOpenness's build);
604// kOpFp64Diag = AC alone, by cutcellBuildFaceOpCell's identical expression over the same box (the
605// level-0 build while the FP64 V-cycle data are deferred, §4.4.7: AC stays the fluid predicate);
606// kOpFp64None = only the weights (the precision setter's rebuild; a deferred coarse level).
607// A face weight t of the box that violates t == 0 || 1e-30 <= t <= 1e30 (the face-range check,
608// §4.4.1 (5)) sets the device flag *bad to 1 (the caller zeroed it); no host reduction, so the
609// build does not block (CutcellMG reads the flags once, at the next solve's eligibility check).
610enum : int { kOpFp64None = 0, kOpFp64Diag = 1, kOpFp64Full = 2 };
611template <class OpV, class WV>
612inline void buildCutcellOpFaceFp32(OpV AC, OpV AFX, OpV AFY, OpV AFZ, WV WX, WV WY, WV WZ,
613 CCConst ox, CCConst oy, CCConst oz, C3 e, int gb, double gfx,
614 double gfy, double gfz, int fp64, int* bad) {
616 "peclet::flow::cc_build_op", C3{0, 0, 0}, C3{e.x, e.y, e.z},
617 KOKKOS_LAMBDA(int lx, int ly, int lz) {
618 const long sx = 1, sy = e.x, sz = (long)e.x * e.y;
619 const long i = (long)lx + (long)ly * sy + (long)lz * sz;
620 if (fp64 != kOpFp64None) {
621 const bool diag =
622 lx >= gb && lx < e.x - gb && ly >= gb && ly < e.y - gb && lz >= gb && lz < e.z - gb;
623 if (fp64 == kOpFp64Full)
624 cutcellBuildFaceOpCell(AC, AFX, AFY, AFZ, ox, oy, oz, i, sx, sy, sz, gfx, gfy, gfz,
625 diag);
626 else if (diag) { // cutcellBuildFaceOpCell's AC, the identical expression
627 const double tw = ox(i) * gfx, ts = oy(i) * gfy, tb = oz(i) * gfz;
628 const double te = ox(i + sx) * gfx;
629 const double tn = oy(i + sy) * gfy;
630 const double tt = oz(i + sz) * gfz;
631 AC(i) = te + tw + tn + ts + tt + tb;
632 }
633 }
634 const double tw = ox(i) * gfx;
635 const double ts = oy(i) * gfy;
636 const double tb = oz(i) * gfz;
637 WX(i) = (VReal)tw;
638 WY(i) = (VReal)ts;
639 WZ(i) = (VReal)tb;
640 const bool okw = tw == 0.0 || (tw >= 1e-30 && tw <= 1e30);
641 const bool oks = ts == 0.0 || (ts >= 1e-30 && ts <= 1e30);
642 const bool okb = tb == 0.0 || (tb >= 1e-30 && tb <= 1e30);
643 if (!(okw && oks && okb))
644 Kokkos::atomic_max(bad, 1);
645 });
646}
647inline void prolongAdd(CCField fine, CCConst coarse, C3 fext, C3 cext, int gf, int gc, C3 finner,
648 C3 ratio) {
649 ccFor3(
650 "peclet::flow::prolong", C3{0, 0, 0}, C3{finner.x, finner.y, finner.z},
651 KOKKOS_LAMBDA(int ifx, int ify, int ifz) {
652 prolongAddCell(fine, coarse, fext, cext, gf, gc, ratio, ifx, ify, ifz);
653 });
654}
655// A3.3 item 1: prolongAdd's piecewise-constant form (the symmetric pressure V-cycle).
656inline void prolongConstAdd(CCField fine, CCConst coarse, C3 fext, C3 cext, int gf, int gc,
657 C3 finner, C3 ratio) {
658 ccFor3(
659 "peclet::flow::prolong_const", C3{0, 0, 0}, C3{finner.x, finner.y, finner.z},
660 KOKKOS_LAMBDA(int ifx, int ify, int ifz) {
661 prolongConstAddCell(fine, coarse, fext, cext, gf, gc, ratio, ifx, ify, ifz);
662 });
663}
664
665} // namespace peclet::flow
666#include "mg_fp32_vcycle.hpp" // D: the FP32 V-cycle kernels (doc/vof_projection_cost_design.md §4)
667#include "mg_line_relax.hpp" // A2.4: the zebra line smoother (doc/mg_depth_policy.md, WO-7)
668namespace peclet::flow {
669
670// --- The direct bottom solve (doc/vof_step_performance_design.md §5.7, §5.14, §13, §14 H-1) -----
671// On every backend (host backends since §14 H-1) an ELIGIBLE agglomerated bottom (single rank,
672// singular operator, <= 8192 inner cells, 1-64 fluid components (BottomLabelKernel), an axis whose
673// planes hold <= 192 cells; CutcellMG::directBottomIneligible) is solved in ONE launch instead of
674// the host GraphAMG round trip: a single team runs flexible CG (Polak-Ribiere) in FP64 on the
675// bottom level's own operator, preconditioned by the block-tridiagonal FP32 direct factor of
676// mg_bottom_direct.hpp (§13; factored by its own launch once per operator change), to a relative
677// infinity-norm residual of tau = 1e-5 (E3), capped at 100 iterations. The constants are fixed, not
678// setters. Ghost width 1 (single rank). B1's V-cycle preconditioner over a geometric sub-hierarchy
679// (§5.7) was retired by §13 D-4; its code is in the history (the WO-6 / WO-11 commits).
680inline constexpr long kBottomMaxCells = 8192;
681// doc/mg_depth_policy.md §4.1-§4.2: nLevels == 0 is the AUTO pressure-MG depth -- the shallowest
682// D >= kAutoMinLevels whose GLOBAL coarsest grid the bottom engine admits (bottomAdmissible), else
683// the natural end of coarsening; the level loops then run with the cap kAutoMaxLevels.
684// kAnchoredFollowsGrid: false until the note's WO-5 -- an anchored (outflow) operator is then
685// "admitted" at depth kAutoMinLevels, i.e. it keeps the explicit default's hierarchy.
686inline constexpr int kAutoMinLevels = 4;
687inline constexpr int kAutoMaxLevels = 30;
688inline constexpr bool kAnchoredFollowsGrid = false;
689// tau: 1e-5 since E3 (§7 WO-6, Q2): 1e-8, 1e-6 and 1e-5 give the SAME outer iteration count on
690// every one of the 50 bubble-column steps (653 total).
691inline constexpr double kBottomTau = 1e-5;
692inline constexpr int kBottomMaxComponents = 64; // B1b (§5.14): more -> GraphAMG
693inline constexpr int kBottomCap = 100;
694// §14 H-1: the team size of the solve launch on a HOST backend, min(this, team_size_max) (the
695// factor launch: kBottomHostFactorTeam). The factor and M are bitwise independent of T by
696// construction (§13.2), and on a host backend the FCG's reductions are single-lane
697// (BottomKernel::teamSum / teamMax), so the host bottom's bits do not depend on T or
698// OMP_NUM_THREADS; T affects speed only. ONE thread since B1 (doc/vof_distributed_partition_design
699// .md §5.3): M runs the rows as SIMD lanes (BottomDirect::laneSubstitute), ~5-8 us per M on the
700// 16x12x8 walls-y bottom, less than the 23 per-plane team barriers a larger team would add (was 8:
701// one Zen CCX; genoa 24x1, 1 thread: 0.70 ms per solve with the team schedule).
702inline constexpr int kBottomHostTeam = 1;
703// §14 H-1, A(b): the FACTOR launch's host team size. The host schedule (mg_bottom_direct.hpp) has
704// ~2.5 barriers per tile and one-thread diagonal tiles, so it scales little past two threads:
705// bench_bottom_factor (16x12x8 walls-y, P = 12, b = 128) on a loaded 24-core Zen 3, ms per factor,
706// T = 1 / 2 / 3 / 4 / 8: 1.44 / 1.09 / 0.93-1.79 / 0.86-1.70 / 1.43-1.88 -- two is the fastest
707// size that is also stable under load. Bitwise free, like kBottomHostTeam. Genoa (Snellius job
708// 27783375, 1 task x 24 cores, 30 reps, median, walls-y P12 b128): T = 1 / 2 / 4 / 6 / 8 / 24:
709// 2.10 / 1.51 / 1.24 / 1.08 / 1.20 / 2.46 ms -- six is the best there (Q-H3), hence 6.
710inline constexpr int kBottomHostFactorTeam = 6;
711
713 C3 ext{0, 0, 0}, inner{0, 0, 0};
715};
716
717// B1b (§5.14): the fluid components of the bottom level. Deterministic min-label propagation over
718// the faces whose coefficient is > 0 (the face form stores the band sign: AF < 0) between two fluid
719// cells (AC > 1e-30, removeMean's predicate), iterated to its fixed point inside one team kernel:
720// every fluid cell ends with the smallest flat index of its component, whatever the update order
721// (Jacobi sweeps between two buffers here). Then, in flat (label) order, one thread numbers the
722// components 0, 1, ... and counts their cells. Solid cells get -1. Out: comp (ids), cnt (cells per
723// component, the first kBottomMaxComponents), nc(0) = the number of components. Geometry time only.
725 using Member = Kokkos::TeamPolicy<CCExec>::member_type;
726 C3 ext{0, 0, 0}, inner{0, 0, 0};
728 Kokkos::View<int*, CCMem> comp, tmp;
729 Kokkos::View<long*, CCMem> cnt;
730 Kokkos::View<int*, CCMem> nc;
731 // §13.4.2: with a slow axis (slow >= 0), each component's last plane kc(c) (the largest
732 // coordinate along `slow` among its cells) and aug(c) = 1/m_c, m_c = its cells in that plane.
733 int slow = -1;
734 Kokkos::View<int*, CCMem> kc;
735 Kokkos::View<double*, CCMem> aug;
736 KOKKOS_INLINE_FUNCTION long cell(int q, int& lx, int& ly, int& lz) const {
737 const int t = q / inner.x;
738 lx = 1 + (q - t * inner.x);
739 lz = t / inner.y;
740 ly = 1 + (t - lz * inner.y);
741 lz += 1;
742 return (long)lx + (long)ly * ext.x + (long)lz * (long)ext.x * ext.y;
743 }
744 // one Jacobi sweep src -> dst; returns the number of labels that moved
745 KOKKOS_INLINE_FUNCTION int sweep(const Member& t, const Kokkos::View<int*, CCMem>& src,
746 const Kokkos::View<int*, CCMem>& dst) const {
747 const int ninner = inner.x * inner.y * inner.z;
748 const long sy = ext.x, sz = (long)ext.x * ext.y;
749 int moved = 0;
750 Kokkos::parallel_reduce(
751 Kokkos::TeamThreadRange(t, ninner),
752 [&](int q, int& acc) {
753 int lx, ly, lz;
754 const long i = cell(q, lx, ly, lz);
755 int m = src(i);
756 if (m >= 0) {
757 const CcNbrs w = ccWrapNbrs(lx, ly, lz, inner, 1, i, sy, sz);
758 const long nb[6] = {w.xp, w.xm, w.yp, w.ym, w.zp, w.zm};
759 const double cf[6] = {(double)AFX(i + 1), (double)AFX(i), (double)AFY(i + sy),
760 (double)AFY(i), (double)AFZ(i + sz), (double)AFZ(i)};
761 for (int f = 0; f < 6; ++f) {
762 const int lj = src(nb[f]);
763 if (cf[f] < 0.0 && lj >= 0 && lj < m)
764 m = lj;
765 }
766 if (m < src(i))
767 acc += 1;
768 }
769 dst(i) = m;
770 },
771 moved); // a sum (the identity of Max<int> is INT_MIN, not 0)
772 return moved;
773 }
774 KOKKOS_INLINE_FUNCTION void operator()(const Member& t) const {
775 const int ninner = inner.x * inner.y * inner.z;
776 Kokkos::parallel_for(Kokkos::TeamThreadRange(t, ninner), [&](int q) {
777 int lx, ly, lz;
778 const long i = cell(q, lx, ly, lz);
779 comp(i) = (AC(i) > 1e-30f) ? (int)i : -1;
780 });
781 t.team_barrier();
782 for (;;) { // two sweeps per round, so the labels end in `comp`
783 sweep(t, comp, tmp);
784 t.team_barrier();
785 const int moved = sweep(t, tmp, comp);
786 t.team_barrier();
787 if (!moved)
788 break;
789 }
790 Kokkos::single(Kokkos::PerTeam(t), [&]() {
791 int n = 0;
792 for (int q = 0; q < ninner; ++q) { // number the roots in label (flat-index) order
793 int lx, ly, lz;
794 const long i = cell(q, lx, ly, lz);
795 if (comp(i) == (int)i)
796 tmp(i) = n++;
797 }
798 for (int c = 0; c < kBottomMaxComponents; ++c)
799 cnt(c) = 0;
800 for (int q = 0; q < ninner; ++q) {
801 int lx, ly, lz;
802 const long i = cell(q, lx, ly, lz);
803 if (comp(i) >= 0) {
804 const int id = tmp(comp(i));
805 comp(i) = id;
806 if (id < kBottomMaxComponents)
807 cnt(id) += 1;
808 }
809 }
810 nc(0) = n;
811 if (slow >= 0) {
812 long m[kBottomMaxComponents];
813 for (int c = 0; c < kBottomMaxComponents; ++c) {
814 kc(c) = -1;
815 m[c] = 0;
816 }
817 for (int pass = 0; pass < 2; ++pass)
818 for (int q = 0; q < ninner; ++q) {
819 int lx, ly, lz;
820 const long i = cell(q, lx, ly, lz);
821 const int c = comp(i);
822 if (c < 0 || c >= kBottomMaxComponents)
823 continue;
824 const int k = (slow == 0 ? lx : (slow == 1 ? ly : lz)) - 1;
825 if (pass == 0 && k > kc(c))
826 kc(c) = k;
827 else if (pass == 1 && k == kc(c))
828 m[c] += 1;
829 }
830 for (int c = 0; c < kBottomMaxComponents; ++c)
831 aug(c) = m[c] > 0 ? 1.0 / (double)m[c] : 0.0;
832 }
833 });
834 }
835};
836
837// The bottom solve kernel: one TeamPolicy(1, T) launch per bottom solve. FCG in FP64 on the stored
838// operator (A0 cell bodies); M = the direct factor `dir` (FacReal = float in production), whose
839// dir.stat(0) = 0 (a factor that failed even with the largest shift) takes the failure path.
840template <class FacReal = float> // PRECISION-EXEMPT: the FP32 direct factor under an FP64 FCG
842 using Member = Kokkos::TeamPolicy<CCExec>::member_type;
845 CCField x, b, r, p, z, zp, ap; // the bottom's solution and rhs (its x, rhs), FCG vectors
846 int precondOnly = 0; // test hook: z = M(b) and nothing else
847 int noMeanForTest = 0; // test hook: M without the component means' removal
848 int teamAlgorithm = 0; // test hook (U9): M by the team schedule even on a host backend
849 // B1b (§5.14): the bottom's fluid components -- comp(i) in [0, nc) on fluid cells, -1 on cells
850 // with AC <= 1e-30 (which keep x = 0) -- their cell counts, and a scratch for their means.
851 int nc = 1;
852 Kokkos::View<const int*, CCMem> comp;
853 Kokkos::View<const long*, CCMem> ccnt;
854 Kokkos::View<double*, CCMem> cmean;
855 Kokkos::View<double*, CCMem> ks; // the Krylov slots; ks(flagSlot) = 1 on a non-finite scalar
856 int flagSlot = 0;
857 Kokkos::View<int*, CCMem> info; // info(0) = inner iterations of the last solve
858
859 // Every phase is one TeamThreadRange pass over the level followed by a barrier; the matvec reads
860 // periodic neighbours through wrapped indices (the A3 rule, §4.3), with 32-bit index arithmetic.
861 KOKKOS_INLINE_FUNCTION static int nInner(const BottomLevel& l) {
862 return l.inner.x * l.inner.y * l.inner.z;
863 }
864 KOKKOS_INLINE_FUNCTION static int nExt(const BottomLevel& l) {
865 return l.ext.x * l.ext.y * l.ext.z;
866 }
867 // inner cell q (x fastest) -> local coordinates (ghost width 1) and the flat index
868 KOKKOS_INLINE_FUNCTION static long cell(const BottomLevel& l, int q, int& lx, int& ly, int& lz) {
869 const int nx = l.inner.x, ny = l.inner.y;
870 const int t = q / nx;
871 lx = 1 + (q - t * nx);
872 lz = t / ny;
873 ly = 1 + (t - lz * ny);
874 lz += 1;
875 return (long)lx + (long)ly * l.ext.x + (long)lz * (long)l.ext.x * l.ext.y;
876 }
877 // §14 H-1: on a HOST backend every reduction of the FCG skeleton (the dots, the max-norms, the
878 // per-component sums of the mean projections) is computed by ONE lane, in ascending inner index
879 // (= ascending ext index) over the same cell set, and broadcast to the team: its bits are then
880 // independent of the team size and of OMP_NUM_THREADS (about 8 x 1536 FMA per FCG iteration).
881 // A device backend keeps the team reductions.
882 static constexpr bool kHostLane = std::is_same_v<CCMem, Kokkos::HostSpace>;
883 // sum over q in [0, n) of f(q, acc) (f adds its term to acc)
884 template <class F>
885 KOKKOS_INLINE_FUNCTION static double teamSum(const Member& t, int n, const F& f) {
886 double s = 0.0;
887 if constexpr (kHostLane) {
888 Kokkos::single(
889 Kokkos::PerTeam(t),
890 [&](double& v) {
891 double acc = 0.0;
892 for (int q = 0; q < n; ++q)
893 f(q, acc);
894 v = acc;
895 },
896 s);
897 } else {
898 Kokkos::parallel_reduce(Kokkos::TeamThreadRange(t, n), f, s);
899 }
900 return s;
901 }
902 // max over q in [0, n) of f(q, acc) (f raises acc to its term), from 0
903 template <class F>
904 KOKKOS_INLINE_FUNCTION static double teamMax(const Member& t, int n, const F& f) {
905 double s = 0.0;
906 if constexpr (kHostLane) {
907 Kokkos::single(
908 Kokkos::PerTeam(t),
909 [&](double& v) {
910 double acc = 0.0;
911 for (int q = 0; q < n; ++q)
912 f(q, acc);
913 v = acc;
914 },
915 s);
916 } else {
917 Kokkos::parallel_reduce(Kokkos::TeamThreadRange(t, n), f, Kokkos::Max<double>(s));
918 }
919 return s;
920 }
921 KOKKOS_INLINE_FUNCTION double dot(const Member& t, const BottomLevel& l, const CCField& a,
922 const CCField& c) const {
923 return teamSum(t, nInner(l), [&](int q, double& acc) {
924 int lx, ly, lz;
925 const long i = cell(l, q, lx, ly, lz);
926 if (l.AC(i) > 1e-30f)
927 acc += a(i) * c(i);
928 });
929 }
930 // The bottom's mean removal, per fluid component (§5.14): one team reduction per label, in label
931 // order, then one subtraction pass.
932 KOKKOS_INLINE_FUNCTION void removeMeanBottom(const Member& t, const CCField& f) const {
933 const BottomLevel& l = lv;
934 for (int c = 0; c < nc; ++c) {
935 const double s = teamSum(t, nInner(l), [&](int q, double& acc) {
936 int lx, ly, lz;
937 const long i = cell(l, q, lx, ly, lz);
938 if (comp(i) == c)
939 acc += f(i);
940 });
941 Kokkos::single(Kokkos::PerTeam(t), [&]() { cmean(c) = s / (double)ccnt(c); });
942 }
943 t.team_barrier();
944 Kokkos::parallel_for(Kokkos::TeamThreadRange(t, nInner(l)), [&](int q) {
945 int lx, ly, lz;
946 const long i = cell(l, q, lx, ly, lz);
947 const int c = comp(i);
948 if (c >= 0)
949 f(i) -= cmean(c);
950 });
951 t.team_barrier();
952 }
953 // z = M r (§13.4.4): the direct factor's M, then the component means' removal (step 5). With
954 // `keep`, z's previous values go there first.
955 KOKKOS_INLINE_FUNCTION void applyM(const Member& t, const CCField& R, const CCField& Z,
956 const CCField* keep) const {
957 dir.apply(t, R, Z, comp, keep, teamAlgorithm != 0);
958 if (!noMeanForTest)
959 removeMeanBottom(t, Z);
960 }
961 KOKKOS_INLINE_FUNCTION void operator()(const Member& t) const {
962 const BottomLevel& B0 = lv;
963 if (precondOnly) {
964 applyM(t, b, z, nullptr);
965 return;
966 }
967 const long sy = B0.ext.x, sz = (long)B0.ext.x * B0.ext.y;
968 Kokkos::parallel_for(Kokkos::TeamThreadRange(t, nExt(B0)), [&](int i) { x(i) = 0.0; });
969 // r = b on the fluid cells and 0 on the solid ones (GraphAMG's identity rows with a zero rhs)
970 Kokkos::parallel_for(Kokkos::TeamThreadRange(t, nInner(B0)), [&](int q) {
971 int lx, ly, lz;
972 const long i = cell(B0, q, lx, ly, lz);
973 r(i) = (comp(i) >= 0) ? b(i) : 0.0;
974 });
975 t.team_barrier();
976 removeMeanBottom(t, r); // b -= mean_fluid(b), per component
977 // max|r| over the fluid cells
978 auto rmax = [&](int q, double& acc) {
979 int lx, ly, lz;
980 const long i = cell(B0, q, lx, ly, lz);
981 if (B0.AC(i) > 1e-30f) {
982 const double v = Kokkos::fabs(r(i));
983 if (v > acc)
984 acc = v;
985 }
986 };
987 const double r0 = teamMax(t, nInner(B0), rmax);
988 int it = 0;
989 // a direct factor that failed even with the largest shift (non-finite input): the failure path
990 bool fail = dir.stat(0) == 0;
991 if (r0 != 0.0 && !fail) {
992 applyM(t, r, z, nullptr);
993 Kokkos::parallel_for(Kokkos::TeamThreadRange(t, nExt(B0)), [&](int i) { p(i) = z(i); });
994 t.team_barrier();
995 double rz = dot(t, B0, r, z);
996 while (it < kBottomCap) {
997 ++it;
998 // Ap = A_b p: the band apply reading p's periodic neighbours through the wrap
999 Kokkos::parallel_for(Kokkos::TeamThreadRange(t, nInner(B0)), [&](int q) {
1000 int lx, ly, lz;
1001 const long i = cell(B0, q, lx, ly, lz);
1002 const CcNbrs w = ccWrapNbrs(lx, ly, lz, B0.inner, 1, i, sy, sz);
1003 ap(i) = cutcellApplyFaceCell(p, B0.AC, B0.AFX, B0.AFY, B0.AFZ, i, 1L, sy, sz, w.xp, w.xm,
1004 w.yp, w.ym, w.zp, w.zm);
1005 });
1006 t.team_barrier();
1007 const double pAp = dot(t, B0, p, ap);
1008 if (!(Kokkos::isfinite(pAp) && pAp > 1e-300)) {
1009 fail = !Kokkos::isfinite(pAp); // a tiny pAp is a converged direction, not a failure
1010 break;
1011 }
1012 const double a = rz / pAp;
1013 // x += a p; r -= a Ap on the fluid cells (a cell with AC <= 1e-30 keeps x = 0), then
1014 // r -= its component mean, then max|r|
1015 Kokkos::parallel_for(Kokkos::TeamThreadRange(t, nInner(B0)), [&](int q) {
1016 int lx, ly, lz;
1017 const long i = cell(B0, q, lx, ly, lz);
1018 if (comp(i) >= 0) {
1019 x(i) += a * p(i);
1020 r(i) -= a * ap(i);
1021 }
1022 });
1023 t.team_barrier();
1024 removeMeanBottom(t, r);
1025 const double rn = teamMax(t, nInner(B0), rmax);
1026 if (rn <= kBottomTau * r0)
1027 break;
1028 applyM(t, r, z, &zp); // zp = z (the previous one), z = M r
1029 // <r, z - zp>: Polak-Ribiere (robust to M's rounding)
1030 const double rzc = teamSum(t, nInner(B0), [&](int q, double& acc) {
1031 int lx, ly, lz;
1032 const long i = cell(B0, q, lx, ly, lz);
1033 if (B0.AC(i) > 1e-30f)
1034 acc += r(i) * (z(i) - zp(i));
1035 });
1036 const double beta = rzc / rz;
1037 rz = dot(t, B0, r, z);
1038 if (!(Kokkos::isfinite(rz) && Kokkos::isfinite(beta))) {
1039 fail = true;
1040 break;
1041 }
1042 Kokkos::parallel_for(Kokkos::TeamThreadRange(t, nInner(B0)), [&](int q) {
1043 int lx, ly, lz;
1044 const long i = cell(B0, q, lx, ly, lz);
1045 p(i) = z(i) + beta * p(i);
1046 });
1047 t.team_barrier();
1048 }
1049 }
1050 if (fail) { // x = 0 on the bottom and the device flag; the host turns it into solveFailed_
1051 Kokkos::parallel_for(Kokkos::TeamThreadRange(t, nExt(B0)), [&](int i) { x(i) = 0.0; });
1052 Kokkos::single(Kokkos::PerTeam(t), [&]() { ks(flagSlot) = 1.0; });
1053 t.team_barrier();
1054 } else {
1055 removeMeanBottom(t, x); // x -= mean_fluid(x), per component
1056 }
1057 Kokkos::single(Kokkos::PerTeam(t), [&]() { info(0) = it; });
1058 }
1059};
1060
1061// Env-gated MG diagnostics (host printf only, off unless PECLET_FLOW_MG_DEBUG is set):
1062// 1 = level table (per-level global/local dims + coarsening ratio) at build time
1063// 2 = + PCG/V-cycle residual history (Chebyshev: r0, final |r|inf, V-cycles; BiCGStab: the exit
1064// reason and running breakdown/stagnation counts) for the first
1065// PECLET_FLOW_MG_DEBUG_SOLVES (default 3) solves
1066// Used to diagnose decomposition-dependent iteration counts; no effect on the solve itself.
1067inline int mgDebugLevel() {
1068 static const int lv = [] {
1069 const char* e = std::getenv("PECLET_FLOW_MG_DEBUG");
1070 return e ? std::atoi(e) : 0;
1071 }();
1072 return lv;
1073}
1074inline int mgDebugSolves() {
1075 static const int n = [] {
1076 const char* e = std::getenv("PECLET_FLOW_MG_DEBUG_SOLVES");
1077 return e ? std::atoi(e) : 3;
1078 }();
1079 return n;
1080}
1081
1082// Communication-avoiding smoothing (`set_comm_avoiding`): exchange a 2-deep ghost layer once per
1083// red-black PAIR instead of 1-deep before every colour, redundantly re-smoothing the 1-deep ghost
1084// ring of the first colour so the second colour reads exactly the values a per-colour exchange
1085// would have delivered — bit-identical, at half the halo events. Consumed by CutcellMG's coarse
1086// levels and by the momentum RB-GS in flow_ibm.hpp. The two subsystems are switched independently
1087// so a measured regression can be ATTRIBUTED to one of them without a rebuild.
1088enum : int { kCaMomentum = 1, kCaMg = 2, kCaBoth = kCaMomentum | kCaMg };
1089// The default mask: both halves on a host backend, OFF on a device backend (USER 2026-10-29: H100
1090// weak scaling measured CA off 21-39 ms/step faster, bit-identical). set_comm_avoiding overrides
1091// it on any backend.
1092inline constexpr int kCaDefault = std::is_same_v<CCMem, Kokkos::HostSpace> ? kCaBoth : 0;
1093
1095 public:
1096#ifdef PECLET_FLOW_MPI
1097 struct Telescope; // defined after Level
1098#endif
1099 struct Level {
1100 C3 ext, inner, ratio{2, 2, 2}, cfac{1, 1, 1};
1101 C3 og{0, 0, 0}; // block inner origin in GLOBAL cells; {0,0,0} single-rank
1102 // This level's GLOBAL inner dims (== inner single-rank). With og it decides which ranks own a
1103 // global domain face — see touchesGlobalFace(lv, f).
1104 C3 gdim{0, 0, 0};
1105 // doc/mg_depth_policy.md Amendment A2.3, set by assignLineAxes() at the hierarchy build from
1106 // GLOBAL quantities only (gdim, cfac, the metric, theta, the domain BCs: no collective,
1107 // np-independent). strongAspect = A' = min_{b != s} H_b / H_s for the unique strong axis s
1108 // (H_a = hp_a * cfac_a; 0 when no axis is strictly finest); lineAxis = s when the trigger T
1109 // holds on this level, else -1. Read by the line smoother (A2.4, lineRelaxOn).
1110 double strongAspect = 0.0;
1111 int lineAxis = -1;
1112 // A2.4: bit a set iff the level decomposition has ONE block along a (every axis single-rank;
1113 // set from the replicated decomposition in initMpi). The line smoother runs along s only where
1114 // bit s is set; a split s keeps point RB-GS on that level.
1115 int wholeAxes = 7;
1116 // A2.4: the line smoother's scratch c, y, z on a triggered level (lineAxis >= 0), level extent,
1117 // FP64 (allocated with the level's FP64 data, allocLine) and FP32 (with its FP32 data,
1118 // fp32Build); empty elsewhere.
1120 Kokkos::View<VReal*, CCMem> lncf, lnyf, lnzf;
1121 std::size_t n = 0;
1122 // Ghost width of this level's block (1 default; 2 on distributed coarse levels eligible for
1123 // communication-avoiding smoothing — see initMpi). Single-rank always 1 (byte-identical).
1124 int g = 1;
1125 bool caOk = false; // width-2 topology built and every rank's block extent >= 4
1127 // A2 face form (mac_pressure.hpp): the diagonal + one coefficient per face, full extent.
1129 // H-1 (doc/vof_projection_cost_design.md §8, host single rank only): the count of inner FLUID
1130 // cells (AC > 1e-30f, the reductions' predicate) and whether that is every inner cell, set by
1131 // setOpenness at each operator build (noteFluidCells). nFluid < 0: not known -> today's path.
1132 long nFluid = -1;
1133 bool allFluid = false;
1134 // S1 (doc/vof_gpu_coarse_tail_design.md §5.1, device single rank only): the same count in a
1135 // device scalar, counted at each AC build by noteFluidCellsDevice, so removeMean / exitFp32 run
1136 // a single-result (asynchronous) reduction instead of the {sum, count} combined reducer (Kokkos
1137 // 5.1 fences twice on every reduction with two results). nFluidDevValid: counted from the
1138 // current AC (a deferred level is not, until ensureFp64 builds it).
1139 Kokkos::View<long, CCMem> nFluidDev;
1140 bool nFluidDevValid = false;
1141 // D (doc/vof_projection_cost_design.md §4.4.2; single rank, non-bottom levels, built only while
1142 // the V-cycle precision is not 'fp64'): the FP32 face weights w_f = fl32(t_f) > 0 -- no
1143 // diagonal in any precision, D_i is summed from the six weights -- and the FP32 iterates.
1144 // wOk: this level's weights are built from the current openness (whether they passed the
1145 // face-range check, §4.4.1 (5), is CutcellMG::fp32WeightsOk: a device flag).
1146 Kokkos::View<VReal*, CCMem> WX, WY, WZ, xf, rhsf, resf;
1147 bool wOk = false;
1148#ifdef PECLET_FLOW_MPI
1149 std::shared_ptr<GridHaloTopology<3>> halo; // per-level topology (decomposed)
1150 std::shared_ptr<GridHalo<double>> dev; // per-level ghost exchange
1151 // D-dist (doc/vof_projection_distributed_design.md §5.1): the FP32 iterates' ghost exchange on
1152 // the same topology, created by fp32Build on a level that carries the FP32 data (null else).
1153 std::shared_ptr<GridHalo<VReal>> devf;
1154 // K3 (doc/vof_distributed_host_comm_design.md §5.2): the STENCIL halo of the 7-point exchanges
1155 // (the non-CA smoother, the residual, the matvec, their FP32 twins): face ghosts only, and no
1156 // periodic wrap on the level's wrap axes `wrapAxes` (= M_L, bit a set iff the level is ONE
1157 // block along a, no outflow face on a and the inner extent on a is even), which the box
1158 // kernels read in-kernel instead. `dev` (full) stays for the prolong / operator / openness
1159 // fills and CA smoothing. sdevf: the FP32 iterates' twin, created beside devf.
1160 std::shared_ptr<GridHaloTopology<3>> shalo;
1161 std::shared_ptr<GridHalo<double>> sdev;
1162 std::shared_ptr<GridHalo<VReal>> sdevf;
1163 int wrapAxes = 0;
1164 // D-dist (§5.1, WO-D2b1): on the FP32 level that telescopes (fp32Last_), the FP64 correction
1165 // the telescope transition scatter-adds into (level extent; empty elsewhere).
1166 CCField tcorr;
1167 // This level's communicator: comm_ above the first telescope point, the roots-only
1168 // sub-communicator below it. Every collective a LEVEL performs (removeMean's Allreduce, the
1169 // bottom's gather) must use this, not comm_ — see Telescope.
1170 MPI_Comm comm = MPI_COMM_NULL;
1171 // Set on level L when the transition L -> L+1 telescopes: L+1 lives on FEWER ranks (the ORB
1172 // tree truncated one or more levels, BlockDecomposer::agglomerated), and the V-cycle moves
1173 // this level's residual down / correction up through a gather / scatter within disjoint rank
1174 // groups. Null on an ordinary in-place transition.
1175 std::shared_ptr<Telescope> tele;
1176#endif
1177 };
1178#ifdef PECLET_FLOW_MPI
1179 // Coarse-level telescoping (docs/MG_TELESCOPING_PLAN.md). When a per-rank block turns odd the
1180 // in-place coarsening (coarsened(): coarse-local i <-> fine-local 2i on the SAME rank) is
1181 // blocked, and without this the hierarchy simply stops -- at 384^3 on 1536 ranks it dies at a
1182 // block of 3x6x4 with the coarsest global extent still 48, and the pressure iteration count
1183 // grows 16.6 -> 38.7 across the ladder. Merging ORB siblings restores parity (the merged block's
1184 // origin is its parent's split value), so: gather level L at ITS OWN resolution onto the group
1185 // roots, and let the roots continue the geometric hierarchy on a sub-communicator. Ranks that
1186 // are not roots idle below L (they join the gather and the scatter, on the parent comm, and skip
1187 // the recursion). restrictAvg/prolongAdd/coarsenOpenAvg are untouched: they read fine INNER
1188 // cells only / write fine INNER cells only, so the stage needs no halo of its own.
1189 //
1190 // The target, the communicators and the movement are core's (suite decision "Coarse-level
1191 // redistribution lives in core; the hierarchies stay in the methods",
1192 // amr/docs/amr_mg_core_boundary.md §7): the depth search is `chooseStageTarget` /
1193 // `shallowestLiftableMerge` with flow's per-axis lift rule as the predicate, the group / roots
1194 // communicators are `makeStageComm`'s, and the gather / scatter of a level field is a
1195 // `RedistributeTopology` built once here and run every V-cycle. What stays in flow: this struct
1196 // (flow's per-level record of a stage), the stage buffers, the scatter's ADD (core's backward
1197 // overwrites) and the WO-R2 outflow ghost-plane gather (teleGatherPlane), which moves a plane
1198 // beyond the inner block that the inner-cell topology does not describe.
1199 struct Telescope {
1200 // group = this rank's group (the ranks merged into one block, owner first), sub = the roots
1201 // only (MPI_COMM_NULL on members). Owned and freed by the StageComm.
1202 peclet::core::decomp::StageComm comm;
1203 bool root() const { return comm.active; } // this rank owns the merged block
1204 bool repartition() const { return comm.kind == peclet::core::decomp::StageKind::Repartition; }
1205 int nMembers = 1;
1206 int g = 1; // ghost width of level L (the stage buffers use it)
1207 C3 mInner{}, mOg{}, mExt{}; // merged block (root): inner dims, global origin, extent
1208 // per-member fine block geometry in group-rank order (root first), root only
1209 std::vector<C3> memO, memS;
1210 // the movement of a level-L field: this rank's inner cells <-> the merged block's (root)
1211 peclet::core::decomp::RedistributeTopology<3, double> move;
1212 // Repartition only: the level's decomposition and the target's (replicated), which the
1213 // outflow ghost-plane movement (teleGatherPlaneRepartition) intersects.
1214 peclet::core::decomp::BlockDecomposer<3> srcDec, dstDec;
1215 std::vector<double> back; // teleScatterAdd's landing buffer, level L's padded layout
1216 CCField res, x, ox, oy, oz; // stage buffers at resolution L on the merged block (root)
1217 };
1218#endif
1219 static constexpr int G = 1; // level-0 / single-rank ghost width (the flow_ibm g=1 bridge)
1220 // The red-black parity origin for a level's smoother: the parity convention is the single-rank
1221 // g=1 one (parity of og+local index INCLUDING a 1-cell ghost offset), so a level with g=2 must
1222 // shift its origin by g-1 per axis or its colours come out swapped against the g=1 reference
1223 // (3 axes -> parity flips). og itself stays the true global inner origin (buildAmg needs it).
1224 static C3 parityOg(const Level& lv) {
1225 return C3{lv.og.x - lv.g + 1, lv.og.y - lv.g + 1, lv.og.z - lv.g + 1};
1226 }
1227
1228 // ---- the aspect-ratio coarsening rule (doc/anisotropic_metric.md §5) -------------------------
1229 // Shared by BOTH geometric hierarchies (VelocityMG calls it too): given this level's spacings
1230 // H[a] = hp[a] * cfac[a] and the per-axis coarsenability canA[a] that today's tests produce
1231 // (canHalve(dim) single-rank, plus evenBlocksOn(dec, a) under MPI), return the per-axis
1232 // coarsening ratio.
1233 //
1234 // aniso == false : ratio_a = 2 iff canA[a] -- TODAY'S DECISION, VERBATIM
1235 // aniso == true : ratio_a = 2 iff canA[a] and H[a] < theta * min_{b : canA[b]} H[b]
1236 //
1237 // i.e. always coarsen the finest coarsenable axis and DEFER one that is already at least theta
1238 // times coarser (§5.2: the spread halves per level until it is below theta and then stays
1239 // there, so no coarse operator is ever more than theta^2 anisotropic in coefficient). On an
1240 // isotropic metric every H in the candidate set is equal, 1 < theta, and the result is today's
1241 // table bit for bit -- which is why the isotropic path is gated on the flag and not on the
1242 // arithmetic (§5.4: the rule WOULD change the table after a telescoping merge).
1243 //
1244 // A DEFERRED axis is not a BLOCKED one: initMpi's telescope trigger keeps reading canA, so
1245 // deferral alone never merges ranks (trap 6).
1246 static C3 mgChooseRatio(const double H[3], const bool canA[3], bool aniso, double theta) {
1247 C3 r{1, 1, 1};
1248 if (!aniso) {
1249 if (canA[0])
1250 r.x = 2;
1251 if (canA[1])
1252 r.y = 2;
1253 if (canA[2])
1254 r.z = 2;
1255 return r;
1256 }
1257 double hmin = 0.0;
1258 bool any = false;
1259 for (int a = 0; a < 3; ++a)
1260 if (canA[a] && (!any || H[a] < hmin)) {
1261 hmin = H[a];
1262 any = true;
1263 }
1264 if (!any)
1265 return r;
1266 const double lim = theta * hmin;
1267 if (canA[0] && H[0] < lim)
1268 r.x = 2;
1269 if (canA[1] && H[1] < lim)
1270 r.y = 2;
1271 if (canA[2] && H[2] < lim)
1272 r.z = 2;
1273 return r;
1274 }
1275
1276 // ---- the line-relaxation trigger (doc/mg_depth_policy.md Amendment A2.3) --------------------
1277 // On level L of GLOBAL inner dims g and coarsening factors cf (H_a = hp_a * cf_a): s = the unique
1278 // axis with H_s < H_b for both b != s (none: no trigger); A' = min_{b != s} H_b / H_s;
1279 // T(L) <=> L >= 1, !canHalve(g[s]) (globally blocked), A' > theta and no outflow face on s.
1280 // Returns s when T(L) holds, else -1; *aspect receives A' (0 when there is no unique s). Global
1281 // quantities only (no collective, np-independent). An s only DEFERRED by mgChooseRatio, or
1282 // blocked only by evenBlocksOn (§5.4), is not globally blocked. Pure and static: host, once per
1283 // level per build.
1284 static int lineAxisTrigger(int L, C3 g, C3 cf, const double hp[3], double theta, const int bc[6],
1285 double* aspect) {
1286 const double H[3] = {hp[0] * (double)cf.x, hp[1] * (double)cf.y, hp[2] * (double)cf.z};
1287 const int gd[3] = {g.x, g.y, g.z};
1288 int s = -1;
1289 for (int a = 0; a < 3; ++a)
1290 if (H[a] < H[(a + 1) % 3] && H[a] < H[(a + 2) % 3])
1291 s = a;
1292 *aspect = 0.0;
1293 if (s < 0)
1294 return -1;
1295 const double A = std::min(H[(s + 1) % 3], H[(s + 2) % 3]) / H[s];
1296 *aspect = A;
1297 const bool blocked = !canHalve(gd[s]);
1298 const bool outflow = bc[2 * s] == 3 || bc[2 * s + 1] == 3;
1299 return (L >= 1 && blocked && A > theta && !outflow) ? s : -1;
1300 }
1301 // A2.3 on the hierarchy just built (init / initMpi, after the level loop): every level's
1302 // lineAxis / strongAspect from its global dims and cfac. Stores only; changes no other state.
1304 for (int L = 0; L < (int)lv_.size(); ++L)
1305 lv_[L].lineAxis = lineAxisTrigger(L, lv_[L].gdim, lv_[L].cfac, hp_, aspectTheta_, bc_,
1306 &lv_[L].strongAspect);
1307 }
1308
1314 void setMetric(const double hp[3]) {
1315 for (int a = 0; a < 3; ++a)
1316 hp_[a] = hp[a];
1317 aniso_ = !(hp_[0] == 1.0 && hp_[1] == 1.0 && hp_[2] == 1.0);
1318 }
1319
1320 std::vector<C3> levelRatios() const {
1321 std::vector<C3> r;
1322 r.reserve(lv_.size());
1323 for (const auto& v : lv_)
1324 r.push_back(v.ratio);
1325 return r;
1326 }
1327
1328 // build the periodic level hierarchy: per axis, halve inner while even and >=2 (uniform when
1329 // cubic), capped at nLevels (mirrors DistributedPoissonMG::init uniform path).
1330 void init(int nx, int ny, int nz, int nLevels) {
1331 joinPrefactor(); // X: a pending side factor may still read the bottom AFX lv_ is about to free
1332 lv_.clear();
1333 opBuilt_ = false; // D: no operator (and no FP32 weights) on the new hierarchy yet
1334 fp64Stale_ = false;
1335 amg_.reset();
1336 eigWarm_ = false; // D3: the kept power-iteration vectors belong to the old hierarchy
1337 gnxF_ = nx;
1338 gnyF_ = ny;
1339 gnzF_ = nz;
1340 C3 inner{nx, ny, nz}, cf{1, 1, 1};
1341 // doc/mg_depth_policy.md §4.2: nLevels == 0 = AUTO (the first admissible level at depth >= 4
1342 // is the bottom); an explicit nLevels >= 1 takes the loop verbatim (autoStop never set).
1343 const bool autoDepth = nLevels == 0;
1344 const int nLevelsCap = autoDepth ? kAutoMaxLevels : nLevels;
1345 for (int L = 0; L < nLevelsCap; ++L) {
1346 Level v;
1347 v.inner = inner;
1348 v.gdim = inner; // single-rank: the block IS the global grid
1349 v.ext = C3{inner.x + 2 * G, inner.y + 2 * G, inner.z + 2 * G};
1350 v.cfac = cf;
1351 v.n = (std::size_t)v.ext.x * v.ext.y * v.ext.z;
1352 C3 next = inner;
1353 C3 ratio{1, 1, 1};
1354 const bool autoStop = autoDepth && L + 1 >= kAutoMinLevels && bottomAdmissibleHere(inner);
1355 if (L + 1 < nLevelsCap && !autoStop) {
1356 // §5.1: the candidate set is today's `canHalve()` per axis; the aspect rule then defers an
1357 // axis that is already >= theta times coarser than the finest candidate. Inert when
1358 // !aniso_.
1359 const bool canA[3] = {canHalve(inner.x), canHalve(inner.y), canHalve(inner.z)};
1360 ratio = levelRatio(inner, cf, canA, next);
1361 }
1362 v.ratio = ratio;
1363 // D5 (doc/vof_projection_cost_design.md §4.4.7): here only what every precision reads --
1364 // every level's openness, level 0's AC (the fluid predicate, nFluid) and x (the drivers'
1365 // staging of the solution: solvePCG, solveFCG, solveBiCGStab). The FP64 V-cycle data
1366 // (allocFp64) come with the first operator build that needs them; the bottom keeps all.
1367 if (L == 0) {
1368 v.x = CCField("mg_x", v.n);
1369 v.AC = FPV("mg_A", v.n);
1370 }
1371 v.nFluidDev = Kokkos::View<long, CCMem>("mg_nfluid");
1372 v.ox = CCField("mg_ox", v.n);
1373 v.oy = CCField("mg_oy", v.n);
1374 v.oz = CCField("mg_oz", v.n);
1375 lv_.push_back(v);
1376 if (next.x == inner.x && next.y == inner.y && next.z == inner.z)
1377 break; // nothing coarsens
1378 inner = next;
1379 cf = C3{cf.x * ratio.x, cf.y * ratio.y, cf.z * ratio.z};
1380 }
1381 assignLineAxes(); // A2.3
1382 allocFp64(lv_.back()); // the bottom level is whole in every precision
1383 buildBottomStore(); // the direct bottom's storage (single rank, every backend)
1385 if (mgDebugLevel()) {
1386 const C3 lb = lv_.back().inner;
1387 const bool more = (lb.x % 2 == 0 && lb.x / 2 >= 2) || (lb.y % 2 == 0 && lb.y / 2 >= 2) ||
1388 (lb.z % 2 == 0 && lb.z / 2 >= 2);
1389 printf("[mg] init %dx%dx%d single-rank -> %d levels (requested %s)\n", nx, ny, nz,
1390 (int)lv_.size(), depthRequestLabel(nLevels).c_str());
1392 for (int L = 0; L < (int)lv_.size(); ++L)
1393 printf("[mg] L%d dims %4dx%4dx%4d ratio(%d,%d,%d)%s\n", L, lv_[L].inner.x, lv_[L].inner.y,
1394 lv_[L].inner.z, lv_[L].ratio.x, lv_[L].ratio.y, lv_[L].ratio.z,
1395 lineAxisLabel(L).c_str());
1396 fflush(stdout);
1397 }
1398 }
1399#ifdef PECLET_FLOW_MPI
1400 // Multi-rank hierarchy: coarsen the GLOBAL grid 2:1 per level; each level gets its own core halo
1401 // over a BlockDecomposer of that level's grid (the ORB decomposition coarsens cleanly so
1402 // restrict/prolong stay local). Sets the distributed flag -> fill() exchanges, the reductions
1403 // Allreduce, the smoother uses the block's global-origin parity. Single-rank (size 1) reproduces
1404 // init()'s field exactly.
1405 // dec0: OPTIONAL shared level-0 decomposition (load-balance / CFD-DEM co-decomposition). When
1406 // given, level 0 uses it so the MG's level-0 block matches the caller's (possibly weighted)
1407 // block, and each coarse level is the previous one coarsened in place while every block stays
1408 // even. nullptr => `decomposition(np, G)` at its defaults: the auto policy (levels 0), which is
1409 // the legacy aligned ORB only where that is exactly balanced (levels 1 = legacy everywhere).
1410 // A WEIGHTED dec0 (rebalanceByWeights) generally has ODD splits: in-place coarsening blocks at
1411 // the shallowest odd split and a telescope stage fires there — at level 0 when the ORB root
1412 // split is odd. The sibling-merge search alone then lands at the shallowest even ORB depth,
1413 // which is ONE RANK (d = 0) whenever the root split is odd: the whole level gathered to one rank
1414 // every V-cycle. Measured (SCALING_ISSUES #2, 96^3 heap, np = 8): projection 2.25-2.6x slower,
1415 // iterations unchanged. The two escapes this comment used to recommend do NOT escape: the
1416 // GraphAMG bottom leaves that level-0 telescope untouched (0.085 -> 0.218 s), and nLevels == 1
1417 // either runs the redundant GraphAMG on the whole grid (the `auto` bottom, ~55x slower) or pure
1418 // RB-GS (the smoother bottom, slower than the collapse it replaces). What bounds it is
1419 // setRepartition(true), which the Solver sets for a weighted dec0: a stage never hands a rank
1420 // more cells than the largest level-0 block, and a merge that would is replaced by a Repartition
1421 // onto a proportional ORB of the level's grid on np_L ranks (core's chooseStageTarget with
1422 // maxBlockCells > 0, amr/docs/amr_mg_core_boundary.md §11.1-§11.3).
1423
1424 // flow's LIFT rule — "every block can coarsen in place one more time": every block is even in
1425 // origin and size on every axis whose GLOBAL extent `gs` can still halve (canHalve()). An axis
1426 // that cannot halve is not a constraint. This is the predicate core's stage policy
1427 // (peclet::core::decomp::chooseStageTarget) is parameterised on, shared by initMpi and predict.
1428 static bool teleLiftable(const peclet::core::decomp::BlockDecomposer<3>& d, C3 gs) {
1429 const int ga[3] = {gs.x, gs.y, gs.z};
1430 for (int ax = 0; ax < 3; ++ax)
1431 if (canHalve(ga[ax]) && !evenBlocksOn(d, ax))
1432 return false;
1433 return true;
1434 }
1435 // Per-axis split alignment that makes an ORB safely coarsenable by this MG: align[k] =
1436 // 2^(number of times axis k can coarsen, until it turns odd) — the NATURAL MAXIMUM, independent
1437 // of the actual nLevels (over-aligning is harmless: coarsened() still divides cleanly at every
1438 // real level). Depends only on the global grid, so the solver's dec_, the mpi_block() sizing, and
1439 // this MG all compute the SAME value without threading nLevels. The solver builds its shared
1440 // decomposition with this alignment so initMpi derives nested coarse levels via coarsened().
1441 static peclet::core::IVec<3> coarsenAlignment(int gnx, int gny, int gnz) {
1442 C3 gs{gnx, gny, gnz};
1443 peclet::core::IVec<3> a{1, 1, 1};
1444 for (bool any = true; any;) {
1445 any = false;
1446 if (canHalve(gs.x)) {
1447 a[0] *= 2;
1448 gs.x /= 2;
1449 any = true;
1450 }
1451 if (canHalve(gs.y)) {
1452 a[1] *= 2;
1453 gs.y /= 2;
1454 any = true;
1455 }
1456 if (canHalve(gs.z)) {
1457 a[2] *= 2;
1458 gs.z /= 2;
1459 any = true;
1460 }
1461 }
1462 // Cap at 16 = 2^4: all a 5-level in-place hierarchy needs. The cap stays under the AUTO depth
1463 // (doc/mg_depth_policy.md): past it, a level telescopes where a block turns odd. The UNCAPPED
1464 // natural-max over-constrains the ORB on power-of-two-rich grids (e.g. 192^3 -> align 64): the
1465 // split snap then rounds a balanced 96|96 to 128|64 (cascading 2:1 load imbalance), and once
1466 // sub-boxes drop under 2*align the snap is skipped -> unaligned splits -> the even-coarsening
1467 // gate collapses the MG depth (measured: 192^3 np=24 pure-MPI, 27 pressure iters/step vs
1468 // 9, 3.4x step time). With the cap the same case decomposes perfectly evenly and keeps 5 nested
1469 // levels; axes whose natural alignment is smaller are unchanged, deeper hierarchies degrade
1470 // through the existing evenBlocks gate exactly as before.
1471 for (int k = 0; k < 3; ++k)
1472 if (a[k] > 16)
1473 a[k] = 16;
1474 return a;
1475 }
1476
1477 // ---- coarse-first ("decompose coarse, refine upward") decomposition ---------------------------
1478 // `levels` selects how the LEVEL-0 DECOMPOSITION is built: 0 (the default) = the legacy
1479 // aligned-ORB route above; L >= 2 = build the ORB on the grid coarsened L-1 times and refine the
1480 // partition upward, which guarantees L nested levels and balances on the coarse grid instead of
1481 // snapping fine splits afterwards. It is a PARAMETER, not process state: `decomposition()` is a
1482 // pure function of (numBlocks, grid, levels, maxImbalance), so every rank — and every call site
1483 // that must agree on the partition (`flow.mpi_block`, `IbmSolver::initMpi`) — computes the same
1484 // answer without communicating, and two solvers in one process can differ.
1485 // Per-axis coarsening factor a depth-`levels` hierarchy will actually apply: 2^(levels-1),
1486 // bounded by that axis's factors of two (an odd axis never coarsens, so its factor stays 1).
1487 static peclet::core::IVec<3> refineFactor(int gnx, int gny, int gnz, int levels) {
1488 C3 gs{gnx, gny, gnz};
1489 peclet::core::IVec<3> r{1, 1, 1};
1490 for (int L = 1; L < levels; ++L) {
1491 if (canHalve(gs.x)) {
1492 r[0] *= 2;
1493 gs.x /= 2;
1494 }
1495 if (canHalve(gs.y)) {
1496 r[1] *= 2;
1497 gs.y /= 2;
1498 }
1499 if (canHalve(gs.z)) {
1500 r[2] *= 2;
1501 gs.z /= 2;
1502 }
1503 }
1504 return r;
1505 }
1506
1507 // Axes some block of `d` does not span whole (bit k = axis k): the axes the partition cuts.
1508 static unsigned splitAxes(const peclet::core::decomp::BlockDecomposer<3>& d) {
1509 unsigned m = 0;
1510 for (const auto& s : d.sizes())
1511 for (int k = 0; k < 3; ++k)
1512 if (s[k] < d.globalSize()[k])
1513 m |= 1u << k;
1514 return m;
1515 }
1516 // 64-bit FNV-1a fingerprint of a decomposition: global size, block count, every block's origin
1517 // and size, and the ORB tree's split axes and positions. Equal partitions give equal values on
1518 // every rank and build (pure integer arithmetic). Solver::initMpi(dec) agrees it across ranks.
1519 static std::uint64_t fingerprint(const peclet::core::decomp::BlockDecomposer<3>& d) {
1520 std::uint64_t h = 1469598103934665603ull;
1521 auto mix = [&h](long long v) {
1522 for (int b = 0; b < 8; ++b) {
1523 h ^= static_cast<std::uint64_t>((static_cast<unsigned long long>(v) >> (8 * b)) & 0xffu);
1524 h *= 1099511628211ull;
1525 }
1526 };
1527 for (int k = 0; k < 3; ++k)
1528 mix((long long)d.globalSize()[k]);
1529 mix((long long)d.numBlocks());
1530 for (std::size_t b = 0; b < d.numBlocks(); ++b)
1531 for (int k = 0; k < 3; ++k) {
1532 mix((long long)d.origins()[b][k]);
1533 mix((long long)d.sizes()[b][k]);
1534 }
1535 std::vector<int> dim;
1536 std::vector<peclet::core::Index> val;
1537 d.flattenTree(dim, val);
1538 mix((long long)dim.size());
1539 for (std::size_t i = 0; i < dim.size(); ++i) {
1540 mix((long long)dim[i]);
1541 mix((long long)val[i]);
1542 }
1543 return h;
1544 }
1545 // Consecutive in-place coarsenings of `d` from level 0, up to 4, before initMpi's first telescope
1546 // trigger: at each step every still-coarsenable axis has even block origins and sizes
1547 // (teleLiftable) and no block is thinner than 4 cells (the teleMinExtent_ default).
1548 static int nestDepth(const peclet::core::decomp::BlockDecomposer<3>& d0) {
1549 namespace cdec = peclet::core::decomp;
1550 cdec::BlockDecomposer<3> d = d0;
1551 C3 gs{(int)d.globalSize()[0], (int)d.globalSize()[1], (int)d.globalSize()[2]};
1552 int n = 0;
1553 for (; n < 4; ++n) {
1554 if (!(canHalve(gs.x) || canHalve(gs.y) || canHalve(gs.z)) || !teleLiftable(d, gs) ||
1555 cdec::minBlockExtent(d) < 4)
1556 break;
1557 const peclet::core::IVec<3> r{canHalve(gs.x) ? 2 : 1, canHalve(gs.y) ? 2 : 1,
1558 canHalve(gs.z) ? 2 : 1};
1559 d = d.coarsened(r);
1560 gs = C3{gs.x / (int)r[0], gs.y / (int)r[1], gs.z / (int)r[2]};
1561 }
1562 return n;
1563 }
1564
1565 // THE shared level-0 decomposition. Every call site must go through this so the solver's block,
1566 // mpi_block()'s sizing and the MG's level 0 cannot drift apart. Pure: a function of (numBlocks,
1567 // grid, levels, maxImbalance), so every rank and call site computes the same answer without
1568 // communicating (doc/vof_distributed_partition_design.md §5.2).
1569 // levels == 0 (DEFAULT, "auto"): the legacy aligned ORB A when it is exactly balanced (so every
1570 // balanced run keeps its partition bit for bit); else the coarse-first partition with the
1571 // balance-aware split axis (core SplitAxis::Balanced) at depth 5, then 4, the first within
1572 // maxImbalance that nests at least as deep as A (nestDepth(C) >= nestDepth(A)); else the
1573 // balance-aware aligned ORB A2 iff it has a smaller largest block and nests at least
1574 // min(nestDepth(A), 3) levels; else A. A candidate that cuts an axis A leaves whole is never
1575 // taken (the wall-normal invariant's status quo), and one whose split-axis set differs from
1576 // A's only when A's max/mean >= 5/4 (WO-D, §13.4(2)).
1577 // levels == 1: the legacy aligned ORB A (the pre-2026-10 default, for reproducing old np > 1
1578 // partitions).
1579 // levels >= 2: the legacy coarse-first search from depth `levels` down to 2 (longest-axis
1580 // split, unchanged: the pre-2026-10 partitions bit for bit), the deepest within
1581 // maxImbalance, else A.
1582 static peclet::core::decomp::BlockDecomposer<3> decomposition(std::size_t numBlocks, int gnx,
1583 int gny, int gnz, int levels = 0,
1584 double maxImbalance = 1.05) {
1585 using Dec = peclet::core::decomp::BlockDecomposer<3>;
1586 const peclet::core::IVec<3> G{gnx, gny, gnz};
1587 Dec A(numBlocks, G, coarsenAlignment(gnx, gny, gnz)); // legacy: split the longest axis
1588 if (levels == 1)
1589 return A;
1590 // Depth and load balance pull against each other: each extra level doubles the quantum on every
1591 // axis that still coarsens, and a partition built on the coarse grid can only place a split on
1592 // a coarse-cell boundary. So rather than guess a granularity, BUILD each candidate and measure
1593 // its imbalance.
1594 if (!(maxImbalance > 1.0))
1595 maxImbalance = 1.05;
1596 if (levels >= 2)
1597 return legacyCoarseFirst(std::move(A), numBlocks, gnx, gny, gnz, levels, maxImbalance);
1598 return autoDecomposition(std::move(A), numBlocks, gnx, gny, gnz, maxImbalance);
1599 }
1600 // decomposition()'s cell counts: one block's cells, the largest and the smallest block of d, and
1601 // their ratio (infinity when a block is empty).
1602 static std::size_t cellsOf(const peclet::core::IVec<3>& s) {
1603 return static_cast<std::size_t>(s[0]) * static_cast<std::size_t>(s[1]) *
1604 static_cast<std::size_t>(s[2]);
1605 }
1606 static std::size_t largestBlock(const peclet::core::decomp::BlockDecomposer<3>& d) {
1607 std::size_t hi = 0;
1608 for (const auto& s : d.sizes())
1609 hi = std::max(hi, cellsOf(s));
1610 return hi;
1611 }
1612 static std::size_t smallestBlock(const peclet::core::decomp::BlockDecomposer<3>& d) {
1613 std::size_t lo = std::numeric_limits<std::size_t>::max();
1614 for (const auto& s : d.sizes())
1615 lo = std::min(lo, cellsOf(s));
1616 return lo;
1617 }
1618 static double imbalanceOf(const peclet::core::decomp::BlockDecomposer<3>& d) {
1619 const std::size_t lo = smallestBlock(d);
1620 return lo ? static_cast<double>(largestBlock(d)) / static_cast<double>(lo)
1621 : std::numeric_limits<double>::infinity();
1622 }
1623 // Decompose the COARSE grid of depth L -- telling the ORB each coarse cell's true extent, so it
1624 // compares the axes the fine grid would -- then refine the partition upward: blocks are exact
1625 // multiples of r, so every level nests for the full depth. `ok` = false when the coarse grid
1626 // is thinner than the rank count (someone would get an empty block) or nothing coarsens.
1627 static peclet::core::decomp::BlockDecomposer<3> coarseFirst(
1628 std::size_t numBlocks, int gnx, int gny, int gnz, int L, bool& ok,
1629 peclet::core::decomp::SplitAxis axis) {
1630 using Dec = peclet::core::decomp::BlockDecomposer<3>;
1631 ok = false;
1632 const peclet::core::IVec<3> r = refineFactor(gnx, gny, gnz, L);
1633 if (r[0] == 1 && r[1] == 1 && r[2] == 1)
1634 return Dec();
1635 const peclet::core::IVec<3> Gc{gnx / r[0], gny / r[1], gnz / r[2]};
1636 if (cellsOf(Gc) < numBlocks)
1637 return Dec();
1638 Dec coarse;
1639 coarse.init(numBlocks, Gc, peclet::core::IVec<3>{1, 1, 1}, r, axis);
1640 ok = true;
1641 return coarse.refined(r);
1642 }
1643 // decomposition(levels >= 2): the legacy coarse-first search, longest-axis split
1644 // (SplitAxis::Longest) -- bit for bit the pre-2026-10 partitions (review 2026-10-20 #1: published
1645 // benchmarks such as foxberry's DECOMP_LEVELS=7 and channel_dns's DECOMP >= 2 must keep
1646 // reproducing). A is the legacy aligned ORB, the fallback.
1647 static peclet::core::decomp::BlockDecomposer<3> legacyCoarseFirst(
1648 peclet::core::decomp::BlockDecomposer<3> A, std::size_t numBlocks, int gnx, int gny, int gnz,
1649 int levels, double maxImbalance) {
1650 using Dec = peclet::core::decomp::BlockDecomposer<3>;
1651 const peclet::core::IVec<3> one{1, 1, 1};
1652 for (int L = levels; L >= 2; --L) {
1653 bool ok = false;
1654 Dec fine =
1655 coarseFirst(numBlocks, gnx, gny, gnz, L, ok, peclet::core::decomp::SplitAxis::Longest);
1656 if (!ok) {
1657 if (refineFactor(gnx, gny, gnz, L) == one)
1658 break; // nothing coarsens on any axis -- the aligned ORB is all there is
1659 continue;
1660 }
1661 if (imbalanceOf(fine) <= maxImbalance) {
1662 if (mgDebugLevel())
1663 printf("[mg] decomposition: coarse-first depth %d (imbalance %.3f)\n", L,
1664 imbalanceOf(fine));
1665 return fine;
1666 }
1667 }
1668 return A;
1669 }
1670 // decomposition(levels == 0), auto: A-exact, C5/C4, A2 or the A fallback (see decomposition()).
1671 static peclet::core::decomp::BlockDecomposer<3> autoDecomposition(
1672 peclet::core::decomp::BlockDecomposer<3> A, std::size_t numBlocks, int gnx, int gny, int gnz,
1673 double maxImbalance) {
1674 namespace cdec = peclet::core::decomp;
1675 using Dec = cdec::BlockDecomposer<3>;
1676 const peclet::core::IVec<3> G{gnx, gny, gnz}, one{1, 1, 1};
1677 auto report = [&](const char* branch, const Dec& d) {
1678 if (mgDebugLevel())
1679 printf("[mg] decomposition: auto %s (max/min %.3f; legacy %.3f)\n", branch, imbalanceOf(d),
1680 imbalanceOf(A));
1681 };
1682 // A candidate never cuts an axis A leaves whole. WO-D (doc/vof_distributed_partition_design.md
1683 // §13.4(2)): it keeps A's split-axis set unless A's max/mean >= 5/4 (integer form, rank-
1684 // consistent). The axes no rank cuts are the levels' wrap axes, which select the K3/H-7 host
1685 // code paths; the cell count cannot see their cost (+9.4 % at 12x2, legacy max/mean 1.125), so
1686 // a candidate that changes them must buy a >= 20 % cut in the critical rank's cells.
1687 const unsigned axesA = splitAxes(A);
1688 const bool legacyImbalanced =
1689 4 * largestBlock(A) * numBlocks >= 5 * cellsOf(G); // max/mean >= 5/4
1690 auto within = [&](const Dec& d) {
1691 const unsigned ax = splitAxes(d);
1692 return (ax & ~axesA) == 0u && (ax == axesA || legacyImbalanced);
1693 };
1694 // Debug printing only: a candidate that passes every test but the guard's second clause, i.e.
1695 // one the unguarded policy would take, makes the fallback print "A-fallback (guard)".
1696 bool guardHit = false;
1697 auto guardOnly = [&](const Dec& d) { return (splitAxes(d) & ~axesA) == 0u && !within(d); };
1698 if (largestBlock(A) == smallestBlock(A)) {
1699 report("A-exact", A);
1700 return A;
1701 }
1702 // A coarse-first candidate must nest at least as deep as legacy (nestDepth counts the
1703 // minimum-extent rule too); A2 below needs min(nestDepth(A), 3).
1704 const int depthA = nestDepth(A);
1705 for (int L : {5, 4}) {
1706 bool ok = false;
1707 Dec C = coarseFirst(numBlocks, gnx, gny, gnz, L, ok, cdec::SplitAxis::Balanced);
1708 if (!ok) {
1709 if (refineFactor(gnx, gny, gnz, L) == one)
1710 break;
1711 continue;
1712 }
1713 if (smallestBlock(C) > 0 && imbalanceOf(C) <= maxImbalance && within(C) &&
1714 nestDepth(C) >= depthA) {
1715 report(L == 5 ? "C5" : "C4", C);
1716 return C;
1717 }
1718 if (mgDebugLevel() && smallestBlock(C) > 0 && imbalanceOf(C) <= maxImbalance &&
1719 nestDepth(C) >= depthA && guardOnly(C))
1720 guardHit = true;
1721 }
1722 Dec A2;
1723 A2.init(numBlocks, G, coarsenAlignment(gnx, gny, gnz), one, cdec::SplitAxis::Balanced);
1724 if (largestBlock(A2) < largestBlock(A) && nestDepth(A2) >= std::min(depthA, 3) && within(A2)) {
1725 report("A2", A2);
1726 return A2;
1727 }
1728 if (mgDebugLevel() && largestBlock(A2) < largestBlock(A) &&
1729 nestDepth(A2) >= std::min(depthA, 3) && guardOnly(A2))
1730 guardHit = true;
1731 report(guardHit ? "A-fallback (guard)" : "A-fallback", A);
1732 return A;
1733 }
1734
1735#endif
1736 // An axis of GLOBAL extent d can halve once more (even, and the half at least 2).
1737 static bool canHalve(int d) { return (d % 2 == 0) && (d / 2 >= 2); }
1738 // §5.1 on one level (dims gs, coarsening factor cf so far, candidate axes canA): the ratio the
1739 // aspect rule picks; next = the coarse level's dims. Inert when !aniso_.
1740 C3 levelRatio(C3 gs, C3 cf, const bool canA[3], C3& next) const {
1741 const double H[3] = {hp_[0] * (double)cf.x, hp_[1] * (double)cf.y, hp_[2] * (double)cf.z};
1742 const C3 ratio = mgChooseRatio(H, canA, aniso_, aspectTheta_);
1743 if (ratio.x == 2)
1744 next.x = gs.x / 2;
1745 if (ratio.y == 2)
1746 next.y = gs.y / 2;
1747 if (ratio.z == 2)
1748 next.z = gs.z / 2;
1749 return ratio;
1750 }
1751#ifdef PECLET_FLOW_MPI
1752 // Every block of d is even in origin and size on axis ax.
1753 static bool evenBlocksOn(const peclet::core::decomp::BlockDecomposer<3>& d, int ax) {
1754 for (std::size_t b = 0; b < d.sizes().size(); ++b)
1755 if ((d.origins()[b][ax] % 2) || (d.sizes()[b][ax] % 2))
1756 return false;
1757 return true;
1758 }
1759 // Smallest block extent (any rank, any axis) — the same on every rank (the decomposition is
1760 // replicated), so initLevelLayout's ghost-width decision is rank-uniform by construction.
1761 static long minBlockExtentOf(const peclet::core::decomp::BlockDecomposer<3>& d) {
1762 long m = std::numeric_limits<long>::max();
1763 for (const auto& s : d.sizes())
1764 for (int k = 0; k < 3; ++k)
1765 m = std::min(m, (long)s[k]);
1766 return m;
1767 }
1768 // initMpi, level L on decomposition dec (rank curRank of curComm; GLOBAL dims gs, coarsening
1769 // factor cf so far): the ghost width, the halo and faces-only stencil topologies, the wrap
1770 // axes and the block geometry.
1771 void initLevelLayout(Level& v, int L, const peclet::core::decomp::BlockDecomposer<3>& dec,
1772 int curRank, MPI_Comm curComm, C3 gs, C3 cf) const {
1773 std::array<bool, 3> per{true, true, true};
1774 v.halo = std::make_shared<GridHaloTopology<3>>();
1775 // Communication-avoiding smoothing needs a 2-deep ghost layer; give it to the COARSE levels
1776 // (where every halo message is pure latency) whose blocks can carry it (extent >= 4 on every
1777 // rank; below that fall back to the per-colour exchange). Level 0 keeps g=1: its exchanges
1778 // are already overlapped with the interior sweep and the solver's g=1 bridge (openness/rhs/
1779 // phi staging, ghost-projection g=2 staging) assumes it. Only for the periodic/IBM operator
1780 // — with domain BCs (setBoundaryConditions BEFORE initMpi) every level keeps the g=1 layout,
1781 // so that path is byte-identical to the pre-CA code.
1782 // Also off on an ODD periodic global extent: the wrap ring slot then has the opposite
1783 // parity of its image, so the colour-0 ring sweep would update it in the wrong colour.
1784 bool oddPeriodic = false;
1785 for (int a = 0; a < 3; ++a)
1786 oddPeriodic = oddPeriodic || (per[a] && dec.globalSize()[a] % 2 != 0);
1787 const bool ca =
1788 L > 0 && !hasBC_ && (caMode_ & kCaMg) && minBlockExtentOf(dec) >= 4 && !oddPeriodic;
1789 v.g = ca ? 2 : 1;
1790 v.caOk = (v.g == 2);
1791 v.halo->buildTopology(dec, curRank, v.g, per, curComm);
1792 v.comm = curComm;
1793 v.dev = std::make_shared<GridHalo<double>>();
1794 v.dev->init(*v.halo);
1795 v.dev->setLabel("mg L" + std::to_string(L) + " g" + std::to_string(v.g) + " ranks" +
1796 std::to_string(dec.numBlocks()));
1797 // K3 (§5.2): the wrap axes M_L, from the replicated decomposition (every rank agrees), and
1798 // the faces-only stencil topology with `per` cleared on them.
1799 {
1800 std::array<bool, 3> sper = per;
1801 v.wrapAxes = 0;
1802 v.wholeAxes = 0;
1803 for (int a = 0; a < 3; ++a) {
1804 bool oneBlock = true;
1805 for (std::size_t b = 0; b < dec.sizes().size(); ++b)
1806 oneBlock =
1807 oneBlock && dec.origins()[b][a] == 0 && dec.sizes()[b][a] == dec.globalSize()[a];
1808 if (oneBlock)
1809 v.wholeAxes |= 1 << a; // A2.4
1810 const bool outflow = bc_[2 * a] == 3 || bc_[2 * a + 1] == 3;
1811 if (oneBlock && !outflow && dec.globalSize()[a] % 2 == 0) {
1812 v.wrapAxes |= 1 << a;
1813 sper[a] = false;
1814 }
1815 }
1816 v.shalo = std::make_shared<GridHaloTopology<3>>();
1817 v.shalo->buildTopology(dec, curRank, v.g, sper, curComm,
1818 peclet::core::halo::Neighborhood::Faces);
1819 v.sdev = std::make_shared<GridHalo<double>>();
1820 v.sdev->init(*v.shalo);
1821 v.sdev->setLabel("mg L" + std::to_string(L) + " g" + std::to_string(v.g) + " stencil w" +
1822 std::to_string(v.wrapAxes));
1823 }
1824 const auto& idx = v.halo->indexer();
1825 const auto eg = idx.sizeInclGhost(), ino = idx.sizeInner(), oig = idx.originInclGhost();
1826 v.ext = {(int)eg[0], (int)eg[1], (int)eg[2]};
1827 v.inner = {(int)ino[0], (int)ino[1], (int)ino[2]};
1828 v.og = {(int)oig[0] + v.g, (int)oig[1] + v.g,
1829 (int)oig[2] + v.g}; // inner origin == single-rank og=0 at origin 0
1830 v.gdim = gs; // this level's GLOBAL dims (og + inner == gdim -> owns +face)
1831 v.cfac = cf;
1832 v.n = idx.numCellsInclGhost();
1833 }
1834 // Does initMpi's level L (GLOBAL dims gs, decomposition curDec) telescope: telescoping on and
1835 // the in-place coarsening blocked (or the blocks below teleMinExtent_), or the test-only force.
1836 bool teleHere(const peclet::core::decomp::BlockDecomposer<3>& curDec, C3 gs, int L) const {
1837 namespace cdec = peclet::core::decomp;
1838 const bool canAny = canHalve(gs.x) || canHalve(gs.y) || canHalve(gs.z);
1839 // flow's lift rule, the predicate core's stage policy is parameterised on.
1840 auto liftable = [&](const cdec::BlockDecomposer<3>& d) { return teleLiftable(d, gs); };
1841 const bool blocked = !liftable(curDec);
1842 const bool tooSmall =
1843 teleMinExtent_ > 0 && cdec::minBlockExtent(curDec) < (peclet::core::Index)teleMinExtent_;
1844 return canAny && curDec.numBlocks() > 1 &&
1845 ((telescope_ && (blocked || tooSmall)) || teleForce_ == L);
1846 }
1847 // initMpi: a level's fields at its full extent (this path allocates every level's FP64 data).
1848 static void allocLevelFields(Level& v) {
1849 v.x = CCField("mg_x", v.n);
1850 v.rhs = CCField("mg_rhs", v.n);
1851 v.res = CCField("mg_res", v.n);
1852 v.nFluidDev = Kokkos::View<long, CCMem>("mg_nfluid");
1853 v.ox = CCField("mg_ox", v.n);
1854 v.oy = CCField("mg_oy", v.n);
1855 v.oz = CCField("mg_oz", v.n);
1856 for (FPV* p : {&v.AC, &v.AFX, &v.AFY, &v.AFZ})
1857 *p = FPV("mg_A", v.n);
1858 }
1859 // PECLET_FLOW_MG_DEBUG (rank 0): initMpi's hierarchy over `size` ranks, depth census and
1860 // per-level table; gs and curDec are the last level's.
1861 void printMpiHierarchy(int size, int nLevels, C3 gs,
1862 const peclet::core::decomp::BlockDecomposer<3>& curDec) const {
1863 const int gnx = gnxF_, gny = gnyF_, gnz = gnzF_;
1864 printf("[mg] initMpi %dx%dx%d np=%d -> %d levels (requested %s)%s\n", gnx, gny, gnz, size,
1865 (int)lv_.size(), depthRequestLabel(nLevels).c_str(),
1866 telescope_ ? " [telescope ON]" : "");
1867 { // rank 0 roots every stage: gs / curDec are the last level's
1868 bool more = false;
1869 for (int a = 0; a < 3; ++a) {
1870 const int d = a == 0 ? gs.x : (a == 1 ? gs.y : gs.z);
1871 more = more || (canHalve(d) && (telescope_ || evenBlocksOn(curDec, a)));
1872 }
1874 }
1875 C3 g{gnx, gny, gnz};
1876 int ranks = size;
1877 for (int L = 0; L < (int)lv_.size(); ++L) {
1878 printf(
1879 "[mg] L%d global %4dx%4dx%4d ranks %5d rank0 block %4dx%4dx%4d "
1880 "ratio(%d,%d,%d)%s%s\n",
1881 L, g.x, g.y, g.z, ranks, lv_[L].inner.x, lv_[L].inner.y, lv_[L].inner.z, lv_[L].ratio.x,
1882 lv_[L].ratio.y, lv_[L].ratio.z, lineAxisLabel(L).c_str(),
1883 lv_[L].tele ? (lv_[L].tele->repartition() ? " -> REPARTITION" : " -> TELESCOPE") : "");
1884 if (lv_[L].tele) {
1885 int sub = 1;
1886 MPI_Comm_size(lv_[L].tele->comm.sub, &sub);
1887 ranks = sub;
1888 }
1889 g = C3{g.x / lv_[L].ratio.x, g.y / lv_[L].ratio.y, g.z / lv_[L].ratio.z};
1890 }
1891 fflush(stdout);
1892 }
1893 void initMpi(int gnx, int gny, int gnz, int nLevels, MPI_Comm comm,
1894 const peclet::core::decomp::BlockDecomposer<3>* dec0 = nullptr) {
1895 joinPrefactor(); // X: as init(): join the side factor before the levels it reads are freed
1896 lv_.clear();
1897 opBuilt_ = false; // D: no operator (and no FP32 weights) on the new hierarchy yet
1898 amg_.reset();
1899 eigWarm_ = false; // D3: the kept power-iteration vectors belong to the old hierarchy
1900 distributed_ = true;
1901 buildBottomStore(); // reset; the levels do not exist yet (rebuilt after the hierarchy)
1902 comm_ = comm;
1903 gnxF_ = gnx;
1904 gnyF_ = gny;
1905 gnzF_ = gnz;
1906 int rank = 0, size = 1;
1907 MPI_Comm_rank(comm, &rank);
1908 MPI_Comm_size(comm, &size);
1909 C3 gs{gnx, gny, gnz}, cf{1, 1, 1};
1910 // Coarse levels are NESTED: level 0 is the shared solver decomposition (dec0), and each coarse
1911 // level is the previous level's decomposition coarsened IN PLACE (same tree/leaf order, split
1912 // positions halved). This keeps restrict/prolong's coarse-local i <-> fine-local ratio*i
1913 // mapping valid on every rank. (An independent ORB per level does NOT nest — coarse blocks can
1914 // split a different axis than the fine level, sending restrict/prolong out of bounds.)
1915 peclet::core::decomp::BlockDecomposer<3> curDec;
1916 if (dec0) {
1917 curDec = *dec0; // solver's shared decomposition (built aligned; see flow_ibm initMpi)
1918 } else {
1919 curDec = decomposition(static_cast<std::size_t>(size), gs.x, gs.y, gs.z);
1920 }
1921 // Below a telescope point the hierarchy continues on a sub-communicator of the group roots:
1922 // these track the communicator/rank a level is built on (rank == block index at every level,
1923 // by construction of the sub-communicator's keys).
1924 MPI_Comm curComm = comm;
1925 int curRank = rank;
1926 teleActive_ = true;
1927 // setRepartition: a stage never hands a rank more cells than the largest LEVEL-0 block
1928 // (design §11.1 — the finest level's largest block, replicated); 0 = sibling merges only.
1929 const peclet::core::Index maxBlockCells =
1930 repartition_ ? peclet::core::decomp::largestBlockCells(curDec) : 0;
1931 // doc/mg_depth_policy.md §4.2: as init() -- nLevels == 0 = AUTO on the GLOBAL dims gs, which
1932 // are replicated with the bc, the mode and the extent, so every rank resolves the same depth
1933 // without a collective; the bottom level is the last, so no telescope is evaluated there.
1934 const bool autoDepth = nLevels == 0;
1935 const int nLevelsCap = autoDepth ? kAutoMaxLevels : nLevels;
1936 for (int L = 0; L < nLevelsCap; ++L) {
1937 Level v;
1938 initLevelLayout(v, L, curDec, curRank, curComm, gs, cf);
1939 C3 next = gs, ratio{1, 1, 1};
1940 bool idleBelow = false;
1941 const bool autoStop = autoDepth && L + 1 >= kAutoMinLevels && bottomAdmissibleHere(gs);
1942 if (L + 1 < nLevelsCap && !autoStop) {
1943 // Coarsen an axis only if the GLOBAL dim can (canHalve()) AND every rank's block is even on
1944 // that axis, so coarsened() nests exactly. Alignment (coarsenAlignment) makes this hold for
1945 // the full natural depth; on an unaligned/awkward decomposition it used to simply stop
1946 // coarsening that axis (fewer geometric levels) — with telescoping ON, a blocked axis
1947 // instead merges ORB siblings onto fewer ranks and carries on (see Telescope).
1948 const bool doTele = teleHere(curDec, gs, L);
1949 if (doTele) {
1950 if (auto t = teleTarget(curDec, gs, L, maxBlockCells)) {
1951 v.tele = makeTelescope(v, L, curDec, *t, curComm);
1952 if (v.tele->root()) {
1953 curDec = t->dec;
1954 curComm = v.tele->comm.sub;
1955 MPI_Comm_rank(curComm, &curRank);
1956 } else {
1957 idleBelow = true; // this rank holds levels 0..L only
1958 }
1959 }
1960 }
1961 auto evenBlocks = [&](int ax) { return evenBlocksOn(curDec, ax); };
1962 // §5.1 again, with the MPI candidate set: an axis can coarsen when the GLOBAL dim can and
1963 // every rank's (possibly just-merged) block is even on it. The aspect rule then defers
1964 // one that is already >= theta times coarser. Note `blocked` (teleHere) is computed from
1965 // `canHalve()` and `evenBlocksOn()` ALONE (trap 6): an axis deferred here is not blocked
1966 // and must not trigger a telescope merge. Every rank has the same doubles and the same
1967 // decomposition, so this is a pure function -- no communication.
1968 const bool canA[3] = {canHalve(gs.x) && evenBlocks(0), canHalve(gs.y) && evenBlocks(1),
1969 canHalve(gs.z) && evenBlocks(2)};
1970 ratio = levelRatio(gs, cf, canA, next);
1971 }
1972 v.ratio = ratio;
1973 allocLevelFields(v);
1974 lv_.push_back(v);
1975 if (idleBelow) {
1976 teleActive_ = false;
1977 break;
1978 }
1979 if (next.x == gs.x && next.y == gs.y && next.z == gs.z)
1980 break;
1981 gs = next;
1982 cf = C3{cf.x * ratio.x, cf.y * ratio.y, cf.z * ratio.z};
1983 // Next level's decomposition = this level's coarsened in place (nested; preserves rank
1984 // order).
1985 curDec = curDec.coarsened(peclet::core::IVec<3>{ratio.x, ratio.y, ratio.z});
1986 }
1987 assignLineAxes(); // A2.3
1988 for (Level& v : lv_)
1989 allocLine(v); // A2.4: this path allocates every level's FP64 data in the loop above
1990 computeFp32Last(); // D-dist (§5.2): after the hierarchy, before any operator build
1991 buildBottomStore(); // §14 H-6: the host global bottom gb_ (none on a device backend)
1992 if (mgDebugLevel() && rank == 0)
1993 printMpiHierarchy(size, nLevels, gs, curDec);
1994 }
1995 // initMpi's telescope target at level L (global dims gs). Fewest merges (largest tree depth) at
1996 // which EVERY still-coarsenable axis has even blocks — "any axis" would be wrong: it can unblock
1997 // z and leave x frozen at the extent that matters. depth 0 (one block: origin 0, size gs, even
1998 // by canHalve()) always qualifies; with the economic trigger a merged candidate must also stay
1999 // fat enough after the halving that follows. That search is core's `shallowestLiftableMerge`, and
2000 // behind flow's trigger it is `chooseStageTarget` with maxBlockCells = 0 (byte-identical to the
2001 // search flow carried inline until S4). The test-only forced telescope runs the search where
2002 // in-place coarsening is legal, i.e. the search on its own.
2003 std::optional<peclet::core::decomp::StageTarget<3>> teleTarget(
2004 const peclet::core::decomp::BlockDecomposer<3>& curDec, C3 gs, int L,
2005 peclet::core::Index maxBlockCells) const {
2006 namespace cdec = peclet::core::decomp;
2007 // flow's lift rule, the predicate core's stage policy is parameterised on.
2008 auto liftable = [&](const cdec::BlockDecomposer<3>& d) { return teleLiftable(d, gs); };
2009 std::optional<cdec::StageTarget<3>> t;
2010 if (teleForce_ == L) {
2011 if (auto m = cdec::shallowestLiftableMerge(curDec, liftable, teleMinExtent_)) {
2012 t.emplace();
2013 t->kind = cdec::StageKind::SiblingMerge;
2014 t->dec = std::move(m->dec);
2015 t->ownerOf = std::move(m->ownerOf);
2016 t->groupOf = std::move(m->groupOf);
2017 }
2018 } else {
2019 t = cdec::chooseStageTarget(curDec, peclet::core::IVec<3>{gs.x, gs.y, gs.z}, liftable,
2020 teleMinExtent_, maxBlockCells);
2021 if (t->kind != cdec::StageKind::SiblingMerge && t->kind != cdec::StageKind::Repartition)
2022 throw std::logic_error(
2023 "CutcellMG::initMpi: the telescope search found no merge (depth 0 always lifts "
2024 "under flow's rule)");
2025 }
2026 return t;
2027 }
2028 // The telescope stage of level v (level L, decomposition curDec on curComm) onto target t: the
2029 // stage communicator, the target block, the members' fine blocks, the field movement and the
2030 // root's stage buffers.
2031 std::shared_ptr<Telescope> makeTelescope(const Level& v, int L,
2032 const peclet::core::decomp::BlockDecomposer<3>& curDec,
2033 const peclet::core::decomp::StageTarget<3>& t,
2034 MPI_Comm curComm) const {
2035 namespace cdec = peclet::core::decomp;
2036 auto T = std::make_shared<Telescope>();
2037 T->comm = cdec::makeStageComm(curComm, t);
2038 T->g = v.g;
2039 // The target block this rank's data moves into: its merge group's (SiblingMerge — the
2040 // root owns it, the members only feed it), or the one it owns (Repartition; none on a
2041 // rank that idles below).
2042 const int tb = T->repartition() ? T->comm.myTargetBlock : T->comm.myGroup;
2043 if (tb >= 0) {
2044 const auto mb = t.dec.block((std::size_t)tb);
2045 T->mOg = C3{(int)mb.origin[0], (int)mb.origin[1], (int)mb.origin[2]};
2046 T->mInner = C3{(int)mb.size[0], (int)mb.size[1], (int)mb.size[2]};
2047 T->mExt = C3{T->mInner.x + 2 * T->g, T->mInner.y + 2 * T->g, T->mInner.z + 2 * T->g};
2048 }
2049 if (T->repartition()) {
2050 T->srcDec = curDec;
2051 T->dstDec = t.dec;
2052 }
2053 // members in group-comm rank order == ascending old block index (makeStageComm)
2054 for (const int b : T->comm.members) {
2055 const auto fb = curDec.block((std::size_t)b);
2056 T->memO.push_back(C3{(int)fb.origin[0], (int)fb.origin[1], (int)fb.origin[2]});
2057 T->memS.push_back(C3{(int)fb.size[0], (int)fb.size[1], (int)fb.size[2]});
2058 }
2059 T->nMembers = (int)T->comm.members.size();
2060 // The movement: a global cell of this rank's level-L block lives at its padded slot
2061 // (og, g, ext of the level); on the root, a cell of the merged block at the stage
2062 // buffer's (mOg, g, mExt). Built once; teleGather / teleScatterAdd run it.
2063 {
2064 const C3 lo = v.og, le = v.ext, mo = T->mOg, me = T->mExt;
2065 const int lg = v.g, mg = T->g;
2066 using peclet::core::Index;
2067 auto srcIdx = [&](const peclet::core::IVec<3>& c) {
2068 return (Index)(c[0] - lo.x + lg) + (Index)(c[1] - lo.y + lg) * le.x +
2069 (Index)(c[2] - lo.z + lg) * (Index)le.x * le.y;
2070 };
2071 auto dstIdx = [&](const peclet::core::IVec<3>& c) {
2072 return (Index)(c[0] - mo.x + mg) + (Index)(c[1] - mo.y + mg) * me.x +
2073 (Index)(c[2] - mo.z + mg) * (Index)me.x * me.y;
2074 };
2075 T->move.build(curDec, t, T->comm, srcIdx, dstIdx, /*id=*/L);
2076 T->back.assign(v.n, 0.0);
2077 }
2078 if (T->root()) {
2079 const std::size_t mn = (std::size_t)T->mExt.x * T->mExt.y * T->mExt.z;
2080 T->res = CCField("tele_res", mn);
2081 T->x = CCField("tele_x", mn);
2082 T->ox = CCField("tele_ox", mn);
2083 T->oy = CCField("tele_oy", mn);
2084 T->oz = CCField("tele_oz", mn);
2085 }
2086 return T;
2087 }
2088#endif
2089 int nLevels() const { return (int)lv_.size(); }
2090 // D-dist (doc/vof_projection_distributed_design.md §5.2): the last level the FP32 V-cycle runs
2091 // on. Single rank the last non-bottom level; distributed the first telescope point if any level
2092 // telescopes (every rank holds the levels up to it), else the last non-bottom level. -1: none.
2093 int fp32Last() const { return fp32Last_; }
2095 fp32Last_ = (int)lv_.size() - 2;
2096#ifdef PECLET_FLOW_MPI
2097 if (distributed_)
2098 for (int L = 0; L < (int)lv_.size(); ++L)
2099 if (lv_[L].tele) {
2100 fp32Last_ = L;
2101 break;
2102 }
2103#endif
2104 }
2105 Level& level(int L) { return lv_[L]; }
2106
2107 // per-face domain BC types {-x,+x,-y,+y,-z,+z}: 0=periodic, 1/2/4=Neumann (wall/inflow/
2108 // free-slip), 3=Dirichlet (outflow). Default all-periodic -> applyBoundaryOpenness is a no-op
2109 // (periodic/IBM path byte-identical).
2110 void setBoundaryConditions(const int bc[6]) {
2111 hasBC_ = false;
2112 hasOutflow_ = false;
2113 for (int i = 0; i < 6; ++i) {
2114 bc_[i] = bc[i];
2115 if (bc[i])
2116 hasBC_ = true;
2117 if (bc[i] == 3)
2118 hasOutflow_ = true;
2119 }
2120 removeMean_ =
2121 !hasOutflow_; // singular all-Neumann -> remove mean; Dirichlet outflow -> non-singular
2122 }
2123 // hold the pressure/correction ghost at 0 on outflow faces (open face -> Dirichlet p=0). Call
2124 // after every (periodic) fill of a solution / search-direction field, on the level it lives
2125 // (g = that level's ghost width).
2126 void applyOutflowGhost(const Level& lv, CCField x, int g = G) {
2127 if (!hasOutflow_)
2128 return;
2129 B3 e{lv.ext.x, lv.ext.y, lv.ext.z};
2130 for (int a = 0; a < 3; ++a)
2131 for (int s = 0; s < 2; ++s)
2132 if (bc_[2 * a + s] == 3 && touchesGlobalFace(lv, 2 * a + s))
2133 bcZeroPressureGhost(x, e, g, a, s);
2134 }
2135 // Zero-gradient (Neumann) pressure/correction ghost on a wall/inflow face (BC type 1/2), the
2136 // counterpart of applyOutflowGhost's Dirichlet ghost. WHY IT EXISTS (WO-H, 2026-08-30): the
2137 // per-level ghost fill is PERIODIC on all three axes (fill()/GridHalo), so on a walled face a
2138 // level's `x` ghost carries the value from the OPPOSITE side of the domain. Every *operator*
2139 // consumer is immune — the wall face openness is 0, so the smoother/residual/matvec multiply that
2140 // ghost by AW/AE/... = 0 — but `prolongAdd` is NOT: trilinear interpolation reads the coarse
2141 // ghost with weight 1/4 whatever the openness, so the fine cells against a wall were receiving a
2142 // quarter of the coarse correction from the far wall. That teleport is a long-range coupling
2143 // present in P and absent from R, i.e. exactly the asymmetry that broke MG-PCG on domain-BC grids
2144 // (measured: dense-M skew ||M-M^T||F/||M||F 3.5-5.4 % wall-bounded vs 0.8 % periodic, and PCG
2145 // 200/200 vs 7). With the zero-gradient ghost the boundary fine cell simply takes the coarse
2146 // value (0.25*c0 + 0.75*c0 = c0), which is also what the constant-mode-preserving prolongation
2147 // must do. Call after every (periodic) fill of a level's solution field that a prolongation will
2148 // read.
2149 //
2150 // This is the pressure-side counterpart of `VelocityMG::fillProlongBcGhosts` /
2151 // `fillBcGhost` (mac_velocity_mg.hpp), the port of the retired CUDA `mg_fill_bc_ghost_k`: the
2152 // VELOCITY multigrid has always done both halves (Dirichlet 0 AND Neumann zero-gradient) before
2153 // its trilinear prolongation. The pressure MG only ever received the Dirichlet half
2154 // (applyOutflowGhost) — CLAUDE.md's "the trilinear prolongation fills the non-periodic boundary
2155 // ghosts (Neumann -> zero-gradient, Dirichlet -> 0)" described the intent, not the code.
2156 void applyNeumannGhost(const Level& lv, CCField x, int g = G) { applyNeumannGhostT(lv, x, g); }
2157 // D: the FP32 coarse iterate's zero-gradient ghost before the FP32 prolongation (same copies).
2158 void applyNeumannGhost(const Level& lv, VField x, int g = G) { applyNeumannGhostT(lv, x, g); }
2159 template <class V>
2160 void applyNeumannGhostT(const Level& lv, V x, int g) {
2161 if (!hasBC_ || !bcGhost_)
2162 return;
2163 B3 e{lv.ext.x, lv.ext.y, lv.ext.z};
2164 for (int a = 0; a < 3; ++a)
2165 for (int s = 0; s < 2; ++s) {
2166 const int t = bc_[2 * a + s];
2167 if ((t == 1 || t == 2 || t == 4) && touchesGlobalFace(lv, 2 * a + s))
2168 bcNeumannGhostT(x, e, g, a, s);
2169 }
2170 }
2171 // Does this rank's block on level `lv` touch global domain face f? Always true single-rank
2172 // (og = 0 and gdim == inner), so every guarded BC application is byte-identical there.
2173 static bool touchesGlobalFace(const Level& lv, int f) {
2174 const int a = f / 2;
2175 const int o = (a == 0) ? lv.og.x : (a == 1) ? lv.og.y : lv.og.z;
2176 const int n = (a == 0) ? lv.inner.x : (a == 1) ? lv.inner.y : lv.inner.z;
2177 const int gd = (a == 0) ? lv.gdim.x : (a == 1) ? lv.gdim.y : lv.gdim.z;
2178 return (f % 2 == 0) ? (o == 0) : (o + n == gd);
2179 }
2180 // re-impose the non-periodic boundary openness a periodic fill leaves wrong: Neumann wall/inflow
2181 // -> 0 (closed), Dirichlet outflow -> left open. Call after every (periodic) openness fill, per
2182 // level.
2183 // `fine` = the next FINER level (null on level 0). Only the outflow-coefficient path reads it.
2184 void applyBoundaryOpenness(Level& lv, Level* fine = nullptr) {
2185 if (fine) {
2186 CCField fo[3] = {fine->ox, fine->oy, fine->oz};
2187 applyBoundaryOpennessFrom(lv, fo, fine->ext, fine->g, fine->ratio);
2188 } else {
2189 applyBoundaryOpennessFrom(lv, nullptr, C3{0, 0, 0}, 0, C3{1, 1, 1});
2190 }
2191 }
2192 // `fo`/`fext`/`fg`/`fratio` describe the FINE openness this level coarsens its outflow
2193 // coefficient plane from: the finer Level in place, or -- across a telescope point -- the merged
2194 // stage buffers (Telescope::ox/oy/oz on T.mExt with T.g), whose high-side outflow plane
2195 // teleGatherPlane carried over with the inner cells.
2196 void applyBoundaryOpennessFrom(Level& lv, const CCField* fo, C3 fext, int fg, C3 fratio) {
2197 if (!hasBC_)
2198 return;
2199 B3 e{lv.ext.x, lv.ext.y, lv.ext.z};
2200 CCField oa[3] = {lv.ox, lv.oy, lv.oz};
2201 for (int a = 0; a < 3; ++a)
2202 for (int s = 0; s < 2; ++s) {
2203 const int t = bc_[2 * a + s];
2204 if (!touchesGlobalFace(lv, 2 * a + s))
2205 continue; // interior rank boundary: the exchanged openness is the right value
2206 if (t == 1 || t == 2 || t == 4) {
2207 bcSetOpenness(oa[a], e, lv.g, a, s, 0.0); // wall/inflow/free-slip Neumann -> closed
2208 } else if (t == 3) {
2209 if (!outflowCoeff_) {
2210 bcSetOpenness(oa[a], e, lv.g, a, s, 1.0); // outflow -> open (periodic fill wraps)
2211 continue;
2212 }
2213 // WO-R2 item 1: the caller handed a COEFFICIENT field (open_f*rho0/rho_f), so the
2214 // literal 1.0 would overwrite it. Low side = an inner index the caller / the coarsening
2215 // already wrote correctly -> leave it. High side = a ghost index the fill wrapped ->
2216 // restore (level 0) or coarsen from the finer level's own restored plane.
2217 if (s == 0)
2218 continue;
2219 if (fo == nullptr) {
2220 mgRestoreFacePlane(oa[a], CCConst(bcPlane_[a]), lv.ext, lv.g, a, 1);
2221 } else {
2222 mgCoarsenFacePlane(oa[a], CCConst(fo[a]), lv.ext, fext, lv.g, fg, lv.inner, fratio, a,
2223 1);
2224 }
2225 }
2226 }
2227 }
2228 // Save the HIGH-side outflow face plane of a coefficient field before the (periodic/halo) ghost
2229 // fill destroys it. Called on level 0 only; the coarse levels re-derive theirs by averaging.
2231 CCField oa[3] = {lv.ox, lv.oy, lv.oz};
2232 int dims[3] = {lv.ext.x, lv.ext.y, lv.ext.z};
2233 for (int a = 0; a < 3; ++a) {
2234 if (bc_[2 * a + 1] != 3 || !touchesGlobalFace(lv, 2 * a + 1))
2235 continue;
2236 const int b = (a + 1) % 3, c = (a + 2) % 3;
2237 const std::size_t np = (std::size_t)dims[b] * dims[c];
2238 if (bcPlane_[a].extent(0) != np)
2239 bcPlane_[a] = CCField(
2240 Kokkos::view_alloc("peclet::flow::mg_bcplane", Kokkos::WithoutInitializing), np);
2241 mgSaveFacePlane(bcPlane_[a], CCConst(oa[a]), lv.ext, lv.g, a, 1);
2242 }
2243 }
2244
2245 // H-1 (§8): count a level's inner fluid cells once per operator build, with the reductions'
2246 // predicate, so the host reductions can drop the AC read on an all-fluid level and removeMean
2247 // its count reduction. Host single rank only; the device and the distributed path keep their
2248 // kernels (§2 device reduction caveat; the distributed count needs its Allreduce anyway).
2250 lv.nFluid = -1;
2251 lv.allFluid = false;
2252 if (!kHostMemory || distributed_)
2253 return;
2254 C3 e = lv.ext;
2255 const int g = lv.g;
2256 FPV ac = lv.AC;
2257 long cnt = 0;
2258 ccReduce3(
2259 "mgfluidcount", C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g},
2260 KOKKOS_LAMBDA(int x, int y, int z, long& k) {
2261 const long i = (long)x + (long)y * e.x + (long)z * (long)e.x * e.y;
2262 if (ac(i) > 1e-30f)
2263 k += 1;
2264 },
2265 cnt);
2266 lv.nFluid = cnt;
2267 lv.allFluid = cnt == (long)lv.inner.x * lv.inner.y * lv.inner.z;
2268 }
2269 // S1 (doc/vof_gpu_coarse_tail_design.md §5.1): the device twin of noteFluidCells -- the same
2270 // predicate and range, a single-result reduction into the level's device scalar (asynchronous,
2271 // no host read). Device single rank only; elsewhere it only clears the flag.
2273 lv.nFluidDevValid = false;
2274 if constexpr (!kHostMemory) {
2275 if (distributed_ || lv.nFluidDev.data() == nullptr)
2276 return;
2277 C3 e = lv.ext;
2278 const int g = lv.g;
2279 FPV ac = lv.AC;
2280 ccReduce3(
2281 "mgfluidcount", C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g},
2282 KOKKOS_LAMBDA(int x, int y, int z, long& k) {
2283 const long i = (long)x + (long)y * e.x + (long)z * (long)e.x * e.y;
2284 if (ac(i) > 1e-30f)
2285 k += 1;
2286 },
2287 Kokkos::Sum<long, CCMem>(lv.nFluidDev));
2288 lv.nFluidDevValid = true;
2289 }
2290 }
2291 // H-1: the host single-rank all-fluid fast path of the reductions below (same cells, same
2292 // order as the masked body; the device never takes it).
2293 bool hostAllFluid(const Level& lv) const {
2294 return kHostMemory && !distributed_ && lv.nFluid >= 0 && lv.allFluid;
2295 }
2296
2297 // H-2a (§8): the level-0 face field of axis a, as the destination of a caller's per-step
2298 // coefficient builder (single rank, no outflow face: setOpenness then overwrites every ghost by
2299 // the periodic fill and re-imposes the wall faces, so the field's previous ghost content cannot
2300 // leak; the outflow-coefficient plane snapshot would read it, so outflow keeps the copies).
2302 const Level& f = lv_[0];
2303 return a == 0 ? f.ox : (a == 1 ? f.oy : f.oz);
2304 }
2305 bool distributed() const { return distributed_; }
2306
2307 // rediscretized cut-cell operator on every level from the fine face openness (idx2 = 1/dx^2
2308 // fine).
2309 void setOpenness(CCConst ox, CCConst oy, CCConst oz, double idx2, double idy2, double idz2) {
2310 joinPrefactor(); // X: nothing writes the bottom operator while the side factor reads it
2311 Level& f = lv_[0];
2312 // Retained for the exact (matrix-free) level-0 apply, which re-derives the face coefficient
2313 // t_f = open_f * gf instead of reading the assembled band. All three call sites pass grid
2314 // units (1.0) today; store them rather than assume it.
2315 gfx_ = idx2;
2316 gfy_ = idy2;
2317 gfz_ = idz2;
2318 // H-2a (§8): a caller that built its coefficients straight into level 0 (level0Coefficient)
2319 // hands the same Views back -- nothing to stage.
2320 if (ox.data() != f.ox.data())
2321 Kokkos::deep_copy(f.ox, ox);
2322 if (oy.data() != f.oy.data())
2323 Kokkos::deep_copy(f.oy, oy);
2324 if (oz.data() != f.oz.data())
2325 Kokkos::deep_copy(f.oz, oz);
2326 if (outflowCoeff_)
2327 saveOutflowPlanes(f); // WO-R2: the high-side outflow coefficient lives on a ghost index
2328 // that the fill below wraps over -- snapshot it first.
2330 f); // periodic fine-level openness ghosts (the operator reads the + neighbour face);
2331 // idempotent when the caller already filled them, required when it passed inner-only.
2333 f); // re-impose non-periodic wall/inflow faces the periodic fill clobbered
2334 // D5 (§4.4.7): with the FP32 V-cycle data built and an exact outer, the non-bottom levels'
2335 // FP64 V-cycle data are not built here (level 0 keeps AC); ensureFp64 builds them for the
2336 // first reader that needs them.
2337 const bool defer = fp64Deferrable();
2338 fp64Stale_ = defer;
2339 if (!defer)
2340 allocFp64(f);
2341 if (fp32Build(0)) { // D: the FP32 weights in the same kernel (§4.4.2)
2342 buildCutcellOpFaceFp32(f.AC, f.AFX, f.AFY, f.AFZ, f.WX, f.WY, f.WZ, CCConst(f.ox),
2343 CCConst(f.oy), CCConst(f.oz), f.ext, G, idx2, idy2, idz2,
2344 defer ? kOpFp64Diag : kOpFp64Full, fp32RangeFlag(0));
2345 f.wOk = true;
2346 } else
2347 buildCutcellOpFace(f.AC, f.AFX, f.AFY, f.AFZ, CCConst(f.ox), CCConst(f.oy), CCConst(f.oz),
2348 f.ext, G, idx2, idy2, idz2);
2349 noteFluidCells(f);
2351#ifdef PECLET_FLOW_MPI
2352 // A telescope point gathers this level's openness onto the group roots (all group ranks take
2353 // part); the next level coarsens from that stage. A rank idling below holds no next level, so
2354 // the loop simply ends for it after the gather.
2355 if (lv_[0].tele) {
2356 teleGather(lv_[0], lv_[0].ox, lv_[0].tele->ox);
2357 teleGather(lv_[0], lv_[0].oy, lv_[0].tele->oy);
2358 teleGather(lv_[0], lv_[0].oz, lv_[0].tele->oz);
2359 teleGatherOutflowPlanes(lv_[0]);
2360 }
2361#endif
2362 for (int L = 1; L < (int)lv_.size(); ++L) {
2363 Level& c = lv_[L];
2364 Level& fin = lv_[L - 1];
2365#ifdef PECLET_FLOW_MPI
2366 if (fin.tele) {
2367 // Across a telescope point the fine openness is the merged STAGE (inner cells gathered by
2368 // teleGather; the WO-R2 high-side outflow coefficient plane, a ghost index, gathered by
2369 // teleGatherPlane), so the coarse boundary coefficient is coarsened from the stage exactly
2370 // as the in-place path coarsens it from the finer level.
2371 Telescope& T = *fin.tele;
2372 coarsenOpenAvg(c.ox, c.oy, c.oz, CCConst(T.ox), CCConst(T.oy), CCConst(T.oz), c.ext, T.mExt,
2373 c.g, T.g, c.inner, fin.ratio);
2374 fillOpenness(c);
2375 CCField so[3] = {T.ox, T.oy, T.oz};
2376 applyBoundaryOpennessFrom(c, so, T.mExt, T.g, fin.ratio);
2377 } else {
2378#endif
2379 coarsenOpenAvg(c.ox, c.oy, c.oz, CCConst(fin.ox), CCConst(fin.oy), CCConst(fin.oz), c.ext,
2380 fin.ext, c.g, fin.g, c.inner, fin.ratio);
2381 fillOpenness(c); // periodic ghost openness (operator build reads the + neighbour face)
2382 applyBoundaryOpenness(c, &fin); // re-impose non-periodic boundary faces per coarse level
2383#ifdef PECLET_FLOW_MPI
2384 }
2385#endif
2386 const double sx = 1.0 / (double)(c.cfac.x * c.cfac.x),
2387 sy = 1.0 / (double)(c.cfac.y * c.cfac.y),
2388 sz = 1.0 / (double)(c.cfac.z * c.cfac.z);
2389 // Width-2 (CA-eligible) levels also assemble the 1-deep ghost RING of the operator (build
2390 // box widened by 1): the ring rows are a deterministic function of the EXCHANGED openness,
2391 // so they come out bit-identical to the owning rank's inner rows — the redundant ring
2392 // re-smoothing of the CA sweep reads them. Inner rows are computed from the same operands
2393 // as the g-box build (identical). g=1 levels keep the inner-only build.
2394 const bool deferC = defer && L + 1 < (int)lv_.size(); // D5: never the bottom
2395 if (!deferC)
2396 allocFp64(c);
2397 if (fp32Build(L)) { // D: the FP32 weights in the same kernel (§4.4.2)
2398 buildCutcellOpFaceFp32(c.AC, c.AFX, c.AFY, c.AFZ, c.WX, c.WY, c.WZ, CCConst(c.ox),
2399 CCConst(c.oy), CCConst(c.oz), c.ext, c.g == 2 ? c.g - 1 : c.g,
2400 idx2 * sx, idy2 * sy, idz2 * sz, deferC ? kOpFp64None : kOpFp64Full,
2401 fp32RangeFlag(L));
2402 c.wOk = true;
2403 } else
2404 buildCutcellOpFace(c.AC, c.AFX, c.AFY, c.AFZ, CCConst(c.ox), CCConst(c.oy), CCConst(c.oz),
2405 c.ext, c.g == 2 ? c.g - 1 : c.g, idx2 * sx, idy2 * sy, idz2 * sz);
2406 if (deferC) { // no AC on a deferred level: its count comes with ensureFp64
2407 c.nFluid = -1;
2408 c.allFluid = false;
2409 c.nFluidDevValid = false;
2410 } else {
2411 noteFluidCells(c);
2413 }
2414#ifdef PECLET_FLOW_MPI
2415 if (c.tele) {
2416 teleGather(c, c.ox, c.tele->ox);
2417 teleGather(c, c.oy, c.tele->oy);
2418 teleGather(c, c.oz, c.tele->oz);
2419 teleGatherOutflowPlanes(c);
2420 }
2421#endif
2422 }
2423 // The operator (all levels, including the bottom) just changed: invalidate the agglomerated
2424 // GraphAMG bottom solve so the next solve rebuilds it from the CURRENT coefficients. The porous
2425 // and variable-rho paths rebuild the coefficients EVERY STEP — with a stale AMG bottom (frozen
2426 // at the first step's operator) the bottom "solve" answers a different matrix, the V-cycle
2427 // preconditioner drifts inconsistent/indefinite, and the outer PCG eventually breaks down and
2428 // NaNs the projection (observed as a sporadic, data-dependent blow-up in porous CFD-DEM). The
2429 // bottom level is tiny, so the per-step rebuild is negligible next to the V-cycles.
2430 amg_.reset();
2431 amgGlobalN_ = 0;
2432 if (gbActive_)
2433 buildGlobalBottomOp(); // §14 H-6: the global bottom's operator from the gathered openness
2434 // §13: the direct factor is rebuilt at the next direct bottom solve; the components
2435 // (condition 6) are labelled once per hierarchy, here at its first operator build.
2436 facStale_ = true;
2437 if (!bottomConnKnown_ && bottomStore_)
2439#ifdef PECLET_FLOW_MPI
2440 if (distributed_ && kHostMemory && !dirAgreedKnown_)
2441 agreeDirectBottom(); // review note 1: once per hierarchy; setOpenness is collective on comm_
2442#endif
2443 opBuilt_ = true;
2444#ifndef NDEBUG
2446#endif
2447 }
2448
2449 // CG preconditioned by one symmetric V-cycle (solve_pcg port). rhs on level 0; solution left in
2450 // level-0 x. Returns the iteration count. Scratch supplied by the caller (level-0-sized fields).
2451 // Optional star overlay (mode-B fluid-only constraint): the SPD Kron-elimination couplings are
2452 // added to the fine-level matvec only; the hierarchy/preconditioner sees the filtered 7-point
2453 // surrogate it was built from (the symmetric sibling of solveBiCGStab's gp overlay pattern).
2454 // Single-rank v1: the star kernels wrap periodically over the inner grid, so no halo work.
2455 int solvePCG(CCField b, CCField x, CCField r, CCField p, CCField z, CCField Ap, int maxit,
2456 double rtol, int pre, int post, int bottom, const StarOverlay* star = nullptr,
2457 int nStar = 0, C3 nnStar = C3{0, 0, 0}) {
2458 return solveWithRestart(x, maxit, [&](int m) {
2459 return solvePCGAttempt(b, x, r, p, z, Ap, m, rtol, pre, post, bottom, star, nStar, nnStar);
2460 });
2461 }
2462 // R (doc/vof_projection_distributed_design.md §4): the restart wrapper of the public PCG / FCG.
2463 // Under 'auto', an attempt that ran the FP32 V-cycle and did not meet its stop test (a cap, a
2464 // non-finite breakdown, a degenerate direction) is re-solved COLD with the FP64 V-cycle -- x = 0,
2465 // a fresh maxit, the caller's stop reference, no projected guess: bitwise the 'fp64' cold solve
2466 // of the same b -- and 'auto' latches FP64 for the rest of the run (setVcyclePrecision re-arms).
2467 // Forced 'fp32' is never restarted (the measurement mode). No second restart. The decision reads
2468 // only the attempt's count, lastSolveConverged_, lastVcycleFp32_ and vprec_ -- allreduced scalars
2469 // and global mode state -- so every rank takes it alike.
2470 template <class Attempt>
2471 int solveWithRestart(CCField x, int maxit, Attempt&& attempt) {
2472 const int it = attempt(maxit);
2473 if (!(vprec_ == kVcycleAuto && lastVcycleFp32_ && !lastSolveConverged_ && attemptMaxit_ > 0))
2474 return it;
2475 const char* why = solveFailed_ ? "non-finite at iteration"
2476 : it >= attemptMaxit_ ? "capped after"
2477 : "degenerate direction at";
2478 lastDiscardedIters_ = it;
2479 ++vcycleRestarts_;
2480 const bool wasCarriable = fp32Carriable(), wasDeferrable = fp64Deferrable();
2481 fp32Latched_ = true; // as a mode change: FP64 data come with the first FP64 V-cycle
2482 fp32Reconfigure(wasCarriable, wasDeferrable);
2483 Kokkos::deep_copy(CCExec(), x, 0.0); // full extent, ghosts included
2484 struct ColdScope { // the restart attempt is cold: no projected guess, x0 = +0 (H-2c)
2485 CutcellMG& m;
2486 CCField v1;
2487 int hist;
2488 bool zero;
2489 ~ColdScope() {
2490 m.guessV1_ = v1;
2491 m.guessHist_ = hist;
2492 m.zeroGuess_ = zero;
2493 }
2494 } cold{*this, guessV1_, guessHist_, zeroGuess_};
2495 guessV1_ = CCField();
2496 guessHist_ = 0;
2497 zeroGuess_ = true;
2498 const int it2 = attempt(maxit);
2499 if (commRank() == 0)
2500 std::fprintf(stderr,
2501 "peclet::flow CutcellMG: the FP32 V-cycle did not converge this solve (%s %d); "
2502 "re-solved with the FP64 V-cycle in %d iterations; 'auto' stays FP64 for the "
2503 "rest of the run (set_pressure_vcycle_precision re-arms)\n",
2504 why, it, it2);
2505 return it2;
2506 }
2507 // An attempt's V-cycle precision (D, §4.4.5): FP32 on an eligible solve; the R test hook's cap
2508 // on an FP32 attempt's maxit; the attempt's budget, which the restart reads.
2509 bool beginAttemptPrecision(int& maxit) {
2510 const bool f32 = fp32VcycleSolve();
2511 lastVcycleFp32_ = f32;
2512 fp32FaultCount_ = 0; // R test hook (debugSetFp32Fault): kind 2 caps an FP32 attempt
2513 if (f32 && fp32FaultKind_ == 2)
2514 maxit = std::min(maxit, fp32FaultAt_);
2515 attemptMaxit_ = maxit;
2516 return f32;
2517 }
2518 // ISSUES sweep item 6: a non-finite r^T z after the first preconditioner application is a
2519 // FAILED solve, not a converged one. It used to print to stdout, zero the correction and return
2520 // 0 iterations, so a caller's rule-3b "no capped pressure solve" check passed while the
2521 // projection had been handed nothing. Report the cap (the return value) and raise the flag;
2522 // set_pressure_strict(True) turns it into a throw. `who` names the Krylov driver.
2523 int failNonFiniteZ(const char* who, Level& l0, CCField x, int maxit) {
2524 solveFailed_ = true;
2525 printf(
2526 "peclet::flow CutcellMG::%s: preconditioner produced non-finite z; "
2527 "returning zero correction (reported as %d/%d iterations, i.e. a CAPPED solve)\n",
2528 who, maxit, maxit);
2529 Kokkos::deep_copy(CCExec(), x, 0.0);
2530 Kokkos::deep_copy(CCExec(), l0.x, x);
2531 if (strictPressure_ && !restartArmed()) // R (§4): the restart handles it
2532 throw std::runtime_error(std::string("peclet::flow CutcellMG::") + who +
2533 ": preconditioner produced non-finite z (set_pressure_strict)");
2534 return maxit;
2535 }
2536 // This rank's index in the solve's communicator (0 single-rank): the Krylov traces print on
2537 // rank 0.
2538 int commRank() const {
2539 int rank = 0;
2540#ifdef PECLET_FLOW_MPI
2541 if (distributed_)
2542 MPI_Comm_rank(comm_, &rank);
2543#endif
2544 return rank;
2545 }
2546 // The host-scalar attempts' (solvePCGAttempt, solveFCGAttempt) residual of the caller's guess x:
2547 // r = b - A x onto the range; returns r0 = max|r|.
2549 const StarOverlay* star, int nStar, C3 nnStar) {
2550 guessMatvec(l0, Ap, x, star, nStar, nnStar); // r = b - A x
2551 Kokkos::deep_copy(CCExec(), r, b);
2552 axpy(r, -1.0, Ap);
2553 removeMean(l0, r); // compatibility: project rhs/residual onto the range
2554 return maxabs(l0, r);
2555 }
2556 // The stop reference: r0 (the default), or the caller's FULL right-hand-side norm when a
2557 // stop reference is set (setStopReference; only the balanced-force projection sets it).
2558 // With it unset rref IS r0, so `rtol * rref` is bit-for-bit the old test.
2559 double armStopTest(double r0, double rtol) {
2560 const double rref = stopRef_ > 0.0 ? stopRef_ : r0;
2561 cgStopRef_ = rref; // Q18: the exit check (cgTrueResidual) reads the stop test's own scale
2562 cgStopRtol_ = rtol;
2563 return rref;
2564 }
2565 // The host-scalar attempts' Ap = A p (with the "all"-scope mean removal) and p^T Ap.
2566 double matvecPAp(Level& l0, CCField Ap, CCField p, const StarOverlay* star, int nStar,
2567 C3 nnStar) {
2568 guessMatvec(l0, Ap, p, star, nStar, nnStar);
2569 if (meanRemovalAll_)
2570 removeMean(l0, Ap); // A preserves mean-freeness; "fine" scope trusts that
2571 return dot(l0, p, Ap);
2572 }
2573 // The host-scalar attempts' x += alpha p, r -= alpha Ap onto the range; returns max|r|. fuse:
2574 // K4 (§5.4) C2 + C3, the same MPI calls.
2575 double cgUpdate(Level& l0, CCField x, CCField r, CCField p, CCField Ap, double alpha, bool fuse) {
2576 if (fuse)
2577 return pcgUpdateMeanMaxDist(l0, x, r, p, Ap, alpha); // K4 C2 + C3
2578 axpy(x, alpha, p);
2579 axpy(r, -alpha, Ap);
2580 removeMean(l0, r);
2581 return maxabs(l0, r);
2582 }
2583 // x onto the range through level 0's iterate l0.x (the host-scalar drivers' exit).
2585 Kokkos::deep_copy(CCExec(), l0.x, x);
2586 removeMean(l0, l0.x);
2587 Kokkos::deep_copy(CCExec(), x, l0.x);
2588 }
2589 // The host-scalar attempts' p^T Ap guard: true leaves the loop with the last finite iterate. A
2590 // non-finite pAp is a failed solve; pAp <= 1e-300 is a CONVERGED direction.
2591 bool pApBreakdown(double pAp) {
2592 if (!std::isfinite(pAp) || pAp <= 1e-300) {
2593 if (!std::isfinite(pAp))
2594 solveFailed_ = true; // ISSUES sweep item 6 (pAp <= 1e-300 is a CONVERGED direction)
2595 return true; // keep the last finite iterate
2596 }
2597 return false;
2598 }
2599 // The Krylov drivers' stop test on max|r| = rn (traced per iteration): true when converged, it
2600 // then counting this iteration.
2601 bool cgConverged(int& it, double rn, double r0, double rtol, double rref, bool trace) {
2602 if (trace)
2603 printf("[mg] it %3d |r|inf=%.6e r/r0=%.4e\n", it + 1, rn, rn / r0);
2604 if (rn < rtol * rref) {
2605 lastSolveConverged_ = true;
2606 ++it;
2607 return true;
2608 }
2609 return false;
2610 }
2611 // solvePCGAttempt's z = M r and r^T z, summed over the ranks; p = z too when p is given (the
2612 // first application). f32 (§5.7): the FP32 V-cycle takes e = ilogb(rn) from the GLOBAL max the
2613 // host already holds and forms the local r^T z (slot k) in its exit pass; the Allreduce sums it.
2614 // fuse: K4 C4, r^T z from the FP64 V-cycle's level-0 exit pass. Else the V-cycle (A5) and dot().
2615 double pcgPrecondRz(Level& l0, bool f32, bool fuse, CCField z, CCField r, double rn, int k,
2616 CCField p) {
2617 if (f32) {
2618 precondVcycleFp32(z, r, std::ilogb(rn), k, CCField());
2619 if (p.extent(0) != 0)
2620 Kokkos::deep_copy(CCExec(), p, z);
2621#ifdef PECLET_FLOW_MPI
2622 return allreduce(readSlot(k), MPI_SUM_, l0.comm);
2623#else
2624 return allreduce(readSlot(k), MPI_SUM_);
2625#endif
2626 }
2627 if (fuse) {
2628 const double rz = precondDotDist(z, r);
2629 if (p.extent(0) != 0)
2630 Kokkos::deep_copy(CCExec(), p, z);
2631 return rz;
2632 }
2633 precondVcycle(z, r);
2634 if (p.extent(0) != 0)
2635 Kokkos::deep_copy(CCExec(), p, z);
2636 return dot(l0, r, z);
2637 }
2638 // One MG-PCG attempt (R, §4: solvePCG's body before the restart wrapper).
2640 double rtol, int pre, int post, int bottom, const StarOverlay* star,
2641 int nStar, C3 nnStar) {
2642 if (!distributed_) // A6: the single-rank driver keeps its Krylov scalars on the device
2643 return solvePCGResident(b, x, r, p, z, Ap, maxit, rtol, pre, post, bottom, star, nStar,
2644 nnStar);
2645 solveFailed_ = false; // ISSUES sweep item 6: per-solve breakdown flag
2646 lastSolveConverged_ = false; // R (§4): per attempt
2647 OverlayScope overlay(overlaySolve_, star != nullptr);
2648 pre_ = pre;
2649 post_ = post;
2650 bottom_ = bottom;
2651 Level& l0 = lv_[0];
2652 Kokkos::deep_copy(CCExec(), l0.x, x);
2653 // E-dist (doc/vof_projection_distributed_design.md §6 item 3): solvePCGResident's guess branch,
2654 // unfused (distributed); with a projected guess r0 below is rref = max|P b|, the zero-guess
2655 // residual. The guess trace is collective (every rank runs it, rank 0 prints).
2656 const StartResidual s0 = startResidual(b, x, r, Ap, z, star, nStar, nnStar, /*fused=*/false,
2657 /*resident=*/false);
2658 const double r0 = s0.r0;
2659 // D-dist (doc/vof_projection_distributed_design.md §5.7): the FP32 V-cycle on an eligible
2660 // solve (a global decision: fp32VcycleIneligible reads global data only); pcgPrecondRz. The
2661 // driver allreduces its r^T z (the Allreduce dot() spends). z is zeroed once (§5.5: the exit
2662 // writes inner cells only, so the never-exchanged wall ghosts of z and p stay 0).
2663 const bool f32 = beginAttemptPrecision(maxit);
2664 const bool fuseK4 = distKrylovFusion(); // K4 (§5.4): C2-C4, the same MPI calls
2665 const double rref = armStopTest(r0, rtol);
2666 int it = 0;
2667 // Env-gated convergence trace (PECLET_FLOW_MG_DEBUG>=2): |b|inf, r0 and the per-iteration
2668 // residual, so a decomposition-dependent iteration count can be read as a rate (preconditioner
2669 // quality) or a floor (round-off) instead of guessed at.
2670 const int dbgRank = commRank();
2671 const bool trace = mgDebugLevel() >= 2 && dbgSolve_ < mgDebugSolves() && dbgRank == 0;
2672 if (trace)
2673 printf("[mg] solve %d: r0=%.6e rtol=%.1e (pre=%d post=%d bottom=%d)\n", dbgSolve_, r0, rtol,
2674 pre, post, bottom);
2675 ++dbgSolve_;
2676 lastSolveConverged_ = r0 == 0.0; // R (§4): the loop is skipped on a zero residual
2677 // Breakdown guards: a non-finite recurrence scalar means the preconditioner or operator
2678 // produced NaN/Inf (should not happen — the guards fail safe rather than poisoning x with a
2679 // NaN alpha/beta and letting the projection silently corrupt every field downstream).
2680 if (r0 > 0.0 && std::isfinite(r0)) {
2681 if (f32) // §5.5
2682 Kokkos::deep_copy(CCExec(), z, 0.0);
2683 double rz = pcgPrecondRz(l0, f32, fuseK4, z, r, r0, kRz, p); // p = z
2684 if (!std::isfinite(rz))
2685 return failNonFiniteZ("solvePCG", l0, x, maxit);
2686 for (; it < maxit; ++it) {
2687 const double pAp = matvecPAp(l0, Ap, p, star, nStar, nnStar);
2688 if (pApBreakdown(pAp))
2689 break;
2690 const double alpha = rz / pAp;
2691 const double rn = cgUpdate(l0, x, r, p, Ap, alpha, fuseK4);
2692 if (cgConverged(it, rn, r0, rtol, rref, trace))
2693 break;
2694 const double rznew = pcgPrecondRz(l0, f32, fuseK4, z, r, rn, kRzNew, CCField());
2695 const double beta = rznew / rz;
2696 if (!std::isfinite(rznew)) {
2697 solveFailed_ = true; // ISSUES sweep item 6: a breakdown, not a convergence
2698 break; // preconditioner breakdown: keep the last finite iterate
2699 }
2700 aypx(p, beta, z);
2701 rz = rznew;
2702 }
2703 }
2704 finalRemoveMean(l0, x);
2705 if (s0.traceGuess)
2706 guessTraceExit(l0, b, x, r0, s0.r0w, it, guessHist_, star, nStar, nnStar);
2707 return it;
2708 }
2709
2710 // --- A6 (doc/vof_step_performance_design.md §4.4, §5.6): device-resident Krylov scalars -------
2711 // The single-rank MG-PCG driver. The same recurrence as solvePCG's loop, statement for statement,
2712 // with its scalars kept on the device: the reductions land in slots of ks_ (0-d Views over one
2713 // small device array) with the same policy and functor as dot / maxabs / removeMean, alpha and
2714 // beta are formed by one-thread kernels with the same IEEE divisions, and the host reads ONE
2715 // packet {pAp, |r|inf, stop} per iteration -- what the stop test needs -- instead of five scalars
2716 // (two dots, the max, two mean-removal sums). Bit-identical to the host-scalar loop; every exit
2717 // returns the same iteration count and sets the same solveFailed_:
2718 // * pAp non-finite or <= 1e-300: x and r untouched, break without ++it (failed iff non-finite);
2719 // * r^T z non-finite: flagged on the device; the NEXT iteration's packet reports it (its update
2720 // is skipped, x and r untouched) and the index of the iteration that computed it is returned
2721 // -- or, if that was the last one, the read after the loop does;
2722 // * |r|inf < rtol r0: ++it, break.
2723 // The distributed path keeps solvePCG's host-scalar loop unchanged (a device-resident Allreduce
2724 // is not in this design).
2725 enum : int {
2726 kPAp = 0,
2727 kRn = 1,
2729 kBottomFlag = 3, // the device bottom met a non-finite scalar (read with the packet)
2730 kRz = 4,
2735 // E (doc/vof_projection_cost_design.md §5.3): the projected initial guess's ONE host packet
2736 // {rref, G11, G12, G22, g1, g2}, contiguous (kGuessPacket slots from kGRref)
2738 kG11 = 10,
2739 kG12 = 11,
2740 kG22 = 12,
2741 kGb1 = 13,
2742 kGb2 = 14,
2743 // solveChebyshev's growth guard: r^T z of the iteration just preconditioned (local partial)
2745 };
2746 static constexpr int kNSlots = 16;
2747 static constexpr int kGuessPacket = 6;
2748 static constexpr int kPacket = 4; // the per-iteration host packet {pAp, rn, stop, bottomFlag}
2749 static constexpr double kBrkPAp = 1.0, kBrkRz = 2.0; // the stop codes (slot kStop)
2750 Kokkos::View<double*, CCMem> ks_; // the scalar slots
2751 Kokkos::View<long, CCMem> kcnt_; // removeMean's fluid-cell count
2752 // S2 (doc/vof_gpu_coarse_tail_design.md §5.4): the host packets and the one-slot read buffer
2753 // live in pinned host memory (HostSpace on host builds) and are read by an instance-scoped copy
2754 // plus an instance fence -- never an exec-less deep_copy (two global fences + a pageable copy).
2755 using PinnedHost = Kokkos::SharedHostPinnedSpace;
2756 Kokkos::View<double*, PinnedHost> kpk_; // the host packet {pAp, rn, stop, bottomFlag}
2757 Kokkos::View<double*, PinnedHost> kgp_; // E's host packet {rref, G11, G12, G22, g1, g2}
2758 Kokkos::View<double, PinnedHost> krd_; // readSlot's buffer
2759 Kokkos::View<double, PinnedHost> kcz_; // solveChebyshev's lagged r^T z (growth guard)
2761 if (ks_.extent(0) == (std::size_t)kNSlots)
2762 return;
2763 ks_ = Kokkos::View<double*, CCMem>("peclet::flow::mg_krylov_scalars", kNSlots);
2764 kcnt_ = Kokkos::View<long, CCMem>("peclet::flow::mg_mean_count");
2765 kpk_ = Kokkos::View<double*, PinnedHost>("peclet::flow::mg_krylov_packet", kPacket);
2766 kgp_ = Kokkos::View<double*, PinnedHost>("peclet::flow::mg_guess_packet", kGuessPacket);
2767 krd_ = Kokkos::View<double, PinnedHost>("peclet::flow::mg_slot_read");
2768 kcz_ = Kokkos::View<double, PinnedHost>("peclet::flow::mg_cheb_rz");
2769 }
2770 Kokkos::View<double, CCMem> slot(int k) const {
2771 return Kokkos::View<double, CCMem>(ks_.data() + k);
2772 }
2773 double readSlot(int k) const {
2774 Kokkos::deep_copy(CCExec(), krd_, slot(k));
2775 CCExec().fence("peclet::flow::mg_read_slot");
2776 return krd_();
2777 }
2778 void setSlot(int k, double v) { Kokkos::deep_copy(CCExec(), slot(k), v); }
2779 // dot / maxabs into a slot: the SAME policy and functor as dot() / maxabs(), result on the
2780 // device.
2781 void dotTo(Level& lv, CCField a, CCField b, int k) {
2782 C3 e = lv.ext;
2783 const int g = lv.g;
2784 CCField aa = a, bb = b;
2785 FPV ac = lv.AC;
2786 if (hostAllFluid(lv)) { // H-1: no AC read
2788 "mgdot", C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g},
2789 KOKKOS_LAMBDA(int x, int y, int z, double& acc) {
2790 const long i = (long)x + (long)y * e.x + (long)z * (long)e.x * e.y;
2791 acc += aa(i) * bb(i);
2792 },
2793 slot(k));
2794 return;
2795 }
2797 "mgdot", C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g},
2798 KOKKOS_LAMBDA(int x, int y, int z, double& acc) {
2799 const long i = (long)x + (long)y * e.x + (long)z * (long)e.x * e.y;
2800 if (ac(i) > 1e-30f)
2801 acc += aa(i) * bb(i);
2802 },
2803 slot(k));
2804 }
2805 // H-2b (§8): p = z and r^T z into slot k. On the host single-rank fused-wrap V-cycle (even
2806 // level 0 with a coarser level) in ONE pass over the inner cells, with dotTo's body and order:
2807 // there no pass writes a ghost of z (precondVcycle zeroes it, the wrap smoother and residual
2808 // fill nothing, prolongAdd writes inner cells), so z's ghosts are +0 and p's, never copied, stay
2809 // the +0 they always hold. Elsewhere the copy and dotTo (§2: a device sum-fusion can change the
2810 // reduction tree).
2811 void copyDotTo(Level& lv, CCField p, CCField r, CCField z, int k) {
2812 if (!(kHostMemory && fusedWrapSmooth(lv) && lv_.size() > 1)) {
2813 Kokkos::deep_copy(CCExec(), p, z);
2814 dotTo(lv, r, z, k);
2815 return;
2816 }
2817 C3 e = lv.ext;
2818 const int g = lv.g;
2819 CCField pp = p, rr = r, zz = z;
2820 FPV ac = lv.AC;
2821 const bool all = hostAllFluid(lv);
2823 "mgdot", C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g},
2824 KOKKOS_LAMBDA(int x, int y, int zc, double& acc) {
2825 const long i = (long)x + (long)y * e.x + (long)zc * (long)e.x * e.y;
2826 pp(i) = zz(i);
2827 if (all || ac(i) > 1e-30f)
2828 acc += rr(i) * zz(i);
2829 },
2830 slot(k));
2831 }
2832 // C (doc/vof_projection_cost_design.md §6): eligibility of the fused host Krylov kernels of
2833 // solvePCGResident -- host memory, single rank with the precomputed fluid count (H-1), the A3
2834 // wrap reads (no outflow face, no overlay), a singular operator (the mean projection runs), and
2835 // level 0 at the matvec's ghost width. Elsewhere the separate kernels (the device keeps them:
2836 // §2, a device sum-fusion can change the reduction tree).
2837 // C4: a pending request of solvePCGResident to form r^T z (slot k; and p = z when p is
2838 // allocated) in the level-0 exit pass of the next V-cycle; k < 0 = none (every other driver).
2839 struct ExitDot {
2840 int k = -1;
2842 bool done = false;
2843 };
2845 bool hostKrylovFusion() const {
2846 const Level& l0 = lv_[0];
2847 return kHostMemory && fusedWrapReads() && removeMean_ && l0.nFluid >= 0 && l0.g == G;
2848 }
2849 // C1 (§6 (i)): y = A v (matvecOverlap's A3 wrap cell body, exact flux or band form) and
2850 // v^T y into slot k in ONE lane pass over the inner cells, with dotTo's mask, operand order and
2851 // lane order: bitwise to matvecOverlap(l0, y, v) + dotTo(l0, v, y, k). hostKrylovFusion() only.
2852 void matvecDotTo(Level& l0, CCField y, CCField v, int k) {
2853 if (!exactResidual_)
2854 ensureFp64(); // D5 (§4.4.7): the band apply reads level 0's AFX, AFY, AFZ
2855 const C3 e = l0.ext, n = l0.inner;
2856 const int g = G;
2857 CCField yy = y;
2858 CCConst vv = v;
2859 FPV ac = l0.AC;
2860 const bool all = hostAllFluid(l0);
2861 if (exactResidual_) {
2862 CCConst ox = l0.ox, oy = l0.oy, oz = l0.oz;
2863 const double gfx = gfx_, gfy = gfy_, gfz = gfz_;
2865 "peclet::flow::cc_apply_exact_dot", C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g},
2866 KOKKOS_LAMBDA(int lx, int ly, int lz, double& acc) {
2867 const long sx = 1, sy = e.x, sz = (long)e.x * e.y;
2868 const long i = (long)lx + (long)ly * sy + (long)lz * sz;
2869 const CcNbrs w = ccWrapNbrs(lx, ly, lz, n, g, i, sy, sz);
2870 const double a = cutcellApplyExactCell(vv, ox, oy, oz, i, sx, sy, sz, w.xp, w.xm, w.yp,
2871 w.ym, w.zp, w.zm, gfx, gfy, gfz);
2872 yy(i) = a;
2873 if (all || ac(i) > 1e-30f)
2874 acc += vv(i) * a;
2875 },
2876 slot(k));
2877 return;
2878 }
2879 FPC AC = l0.AC, AFX = l0.AFX, AFY = l0.AFY, AFZ = l0.AFZ;
2881 "peclet::flow::cc_apply_dot", C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g},
2882 KOKKOS_LAMBDA(int lx, int ly, int lz, double& acc) {
2883 const long sx = 1, sy = e.x, sz = (long)e.x * e.y;
2884 const long i = (long)lx + (long)ly * sy + (long)lz * sz;
2885 const CcNbrs w = ccWrapNbrs(lx, ly, lz, n, g, i, sy, sz);
2886 const double a = cutcellApplyFaceCell(vv, AC, AFX, AFY, AFZ, i, sx, sy, sz, w.xp, w.xm,
2887 w.yp, w.ym, w.zp, w.zm);
2888 yy(i) = a;
2889 if (all || ac(i) > 1e-30f)
2890 acc += vv(i) * a;
2891 },
2892 slot(k));
2893 }
2894 // C2 (§6 (ii), amendment 4): x += alpha p, r -= alpha Ap (mgpcg_update's expressions, skipped
2895 // once the stop flag is set) over the INNER cells, and the fluid sum of the new r into kMsum
2896 // with removeMeanHostCounted's body and lane order -- bitwise to mgpcg_update + that sum on
2897 // every inner cell. The ghost entries of x and r are no longer updated: no reader consumes
2898 // them (the A3 wrap reads wrap inner cells, the V-cycle reads r's inner cells, the reductions
2899 // and the final removeMean run over inner cells). A stopped iteration adds nothing; its sum is
2900 // never used (the stop-guarded subtract skips). hostKrylovFusion() only.
2902 const C3 e = l0.ext;
2903 const int g = l0.g;
2904 CCField xx = x, rr = r, pp = p, aa = Ap;
2905 FPV ac = l0.AC;
2906 const bool all = l0.allFluid;
2907 auto ks = ks_;
2909 "mgpcg_update_sum", C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g},
2910 KOKKOS_LAMBDA(int x_, int y, int z, double& s) {
2911 if (ks(kStop) != 0.0)
2912 return;
2913 const long i = (long)x_ + (long)y * e.x + (long)z * (long)e.x * e.y;
2914 const double a = ks(kAlpha), na = -a;
2915 xx(i) += a * pp(i);
2916 rr(i) += na * aa(i);
2917 if (all || ac(i) > 1e-30f)
2918 s += rr(i);
2919 },
2920 Kokkos::Sum<double, CCMem>(slot(kMsum)));
2921 }
2922 // C3 (§6 (iii)): removeMeanHostCounted's stop-guarded subtract (mean = kMsum / nFluid) and
2923 // maxabsTo's max|f| over the fluid cells into slot k in one pass. Max is order-free: bitwise
2924 // to mgmeans + mgmax. hostKrylovFusion() only.
2925 void meanSubtractMaxTo(Level& lv, CCField f, int k) {
2926 const C3 e = lv.ext;
2927 const int g = lv.g;
2928 CCField ff = f;
2929 FPV ac = lv.AC;
2930 const bool all = lv.allFluid;
2931 const long cnt = lv.nFluid;
2932 auto ks = ks_;
2933 ccReduce3(
2934 "mgmeans_max", C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g},
2935 KOKKOS_LAMBDA(int x, int y, int z, double& m) {
2936 const long i = (long)x + (long)y * e.x + (long)z * (long)e.x * e.y;
2937 if (!(cnt == 0 || ks(kStop) != 0.0)) {
2938 const double mean = ks(kMsum) / (double)cnt;
2939 if (all)
2940 ff(i) -= mean;
2941 else
2942 meanSubtractCell(ff, ac, i, mean);
2943 }
2944 if (all || ac(i) > 1e-30f) {
2945 const double v = Kokkos::fabs(ff(i));
2946 if (v > m)
2947 m = v;
2948 }
2949 },
2950 Kokkos::Max<double, CCMem>(slot(k)));
2951 }
2952 void maxabsTo(Level& lv, CCField a, int k) {
2953 C3 e = lv.ext;
2954 const int g = lv.g;
2955 CCField aa = a;
2956 FPV ac = lv.AC;
2957 if (hostAllFluid(lv)) { // H-1: no AC read
2958 ccReduce3(
2959 "mgmax", C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g},
2960 KOKKOS_LAMBDA(int x, int y, int z, double& acc) {
2961 const long i = (long)x + (long)y * e.x + (long)z * (long)e.x * e.y;
2962 const double v = Kokkos::fabs(aa(i));
2963 if (v > acc)
2964 acc = v;
2965 },
2966 Kokkos::Max<double, CCMem>(slot(k)));
2967 return;
2968 }
2969 ccReduce3(
2970 "mgmax", C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g},
2971 KOKKOS_LAMBDA(int x, int y, int z, double& acc) {
2972 const long i = (long)x + (long)y * e.x + (long)z * (long)e.x * e.y;
2973 if (ac(i) > 1e-30f) {
2974 const double v = Kokkos::fabs(aa(i));
2975 if (v > acc)
2976 acc = v;
2977 }
2978 },
2979 Kokkos::Max<double, CCMem>(slot(k)));
2980 }
2981 // Test hook (tests/kokkos/test_pcg_breakdown.cpp): poison the pAp (which = 1) or r^T z
2982 // (which = 2) of iteration `iter` of the next single-rank PCG solves with a NaN; which = 0 (the
2983 // default) disarms it. Exercises the breakdown exits, which no healthy problem reaches.
2984 void setDebugBreakdown(int which, int iter) {
2985 dbgBrkWhich_ = which;
2986 dbgBrkIter_ = iter;
2987 }
2988 // --- E (doc/vof_projection_cost_design.md §5.2, §5.3): the projected initial guess ----------
2989 // E1 (§5.3 step 3): y = A v (matvecOverlap's A3 wrap cell body, exact flux or band form, as
2990 // matvecDotTo) with v^T y -> kvy, v^T r -> kvr and, when ND == 3, w^T y -> kwy, in ONE lane
2991 // pass over the inner cells (fluid cells; the 4-lane host order). hostKrylovFusion() only.
2992 template <int ND>
2993 void matvecGuessDots(Level& l0, CCField y, CCField v, CCField w, CCField r, int kvy, int kvr,
2994 int kwy) {
2995 static_assert(ND == 2 || ND == 3, "matvecGuessDots: two or three dots");
2996 if (!exactResidual_)
2997 ensureFp64(); // D5 (§4.4.7): the band apply reads level 0's AFX, AFY, AFZ (as matvecDotTo)
2998 const C3 e = l0.ext, n = l0.inner;
2999 const int g = G;
3000 CCField yy = y;
3001 CCConst vv = v, ww = w, rr = r;
3002 FPV ac = l0.AC;
3003 const bool all = hostAllFluid(l0);
3004 const bool exact = exactResidual_;
3005 CCConst ox = l0.ox, oy = l0.oy, oz = l0.oz;
3006 const double gfx = gfx_, gfy = gfy_, gfz = gfz_;
3007 FPC AC = l0.AC, AFX = l0.AFX, AFY = l0.AFY, AFZ = l0.AFZ;
3008 auto cell = KOKKOS_LAMBDA(int lx, int ly, int lz, long& i)->double {
3009 const long sx = 1, sy = e.x, sz = (long)e.x * e.y;
3010 i = (long)lx + (long)ly * sy + (long)lz * sz;
3011 const CcNbrs nb = ccWrapNbrs(lx, ly, lz, n, g, i, sy, sz);
3012 const double a = exact ? cutcellApplyExactCell(vv, ox, oy, oz, i, sx, sy, sz, nb.xp, nb.xm,
3013 nb.yp, nb.ym, nb.zp, nb.zm, gfx, gfy, gfz)
3014 : cutcellApplyFaceCell(vv, AC, AFX, AFY, AFZ, i, sx, sy, sz, nb.xp,
3015 nb.xm, nb.yp, nb.ym, nb.zp, nb.zm);
3016 yy(i) = a;
3017 return a;
3018 };
3019 if constexpr (ND == 2) {
3021 "peclet::flow::mg_guess_apply_dots", C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g},
3022 KOKKOS_LAMBDA(int lx, int ly, int lz, double& svy, double& svr) {
3023 long i = 0;
3024 const double a = cell(lx, ly, lz, i);
3025 if (all || ac(i) > 1e-30f) {
3026 svy += vv(i) * a;
3027 svr += vv(i) * rr(i);
3028 }
3029 },
3030 Kokkos::Sum<double, CCMem>(slot(kvy)), Kokkos::Sum<double, CCMem>(slot(kvr)));
3031 } else {
3033 "peclet::flow::mg_guess_apply_dots", C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g},
3034 KOKKOS_LAMBDA(int lx, int ly, int lz, double& svy, double& svr, double& swy) {
3035 long i = 0;
3036 const double a = cell(lx, ly, lz, i);
3037 if (all || ac(i) > 1e-30f) {
3038 svy += vv(i) * a;
3039 svr += vv(i) * rr(i);
3040 swy += ww(i) * a;
3041 }
3042 },
3043 Kokkos::Sum<double, CCMem>(slot(kvy)), Kokkos::Sum<double, CCMem>(slot(kvr)),
3044 Kokkos::Sum<double, CCMem>(slot(kwy)));
3045 }
3046 }
3047 // §5.3 step 3, the guess of ONE PCG / FCG solve (guessHist_ > 0; distributed: the packet's five
3048 // sums allreduced with MPI_SUM, then rref with MPI_MAX, doc/vof_projection_distributed_design.md
3049 // §6 item 2): r = P b,
3050 // rref = max|r|; A v1 -> av1 with G11 = v1^T A v1, g1 = v1^T r; with hist 2 (v2 = x = phi^{n-1})
3051 // A v2 -> av2 with G22, G12 = v1^T A v2, g2 = v2^T r; ONE host packet read; the 2x2 Galerkin
3052 // system by Cholesky in double; then x = c1 v1 + c2 v2 on the fluid cells (0 elsewhere, ghosts
3053 // 0) and r -= c1 A v1 + c2 A v2, P r. c = (0, 0) (no positive G11, a non-finite scalar) leaves
3054 // the cold state exactly: x = 0 (full extent), r = P b. Returns rref, the stop reference (the
3055 // zero-guess residual: today's r0 when x0 = 0). `fused`: the host lane kernels (C1's pattern);
3056 // elsewhere the separate matvec and dots (§2 device caveat). *r0w: max|r| after the guess when
3057 // the caller traces (one extra read, trace only).
3058 // The solves' level-0 matvec (matvecOverlap + the optional star overlay) as a member: a
3059 // function-local lambda type may not parameterize a function holding extended device lambdas.
3060 void guessMatvec(Level& l0, CCField y, CCField v, const StarOverlay* star, int nStar, C3 nnStar) {
3061 matvecOverlap(l0, y, v);
3062 if (star)
3063 starApplyDelta(y, CCConst(v), *star, nStar, nnStar, l0.ext, G, l0.ext, G, exactResidual_);
3064 }
3066 const StarOverlay* star, int nStar, C3 nnStar, bool fused, double* r0w) {
3067 auto matvec = [&](CCField y, CCField v) { guessMatvec(l0, y, v, star, nStar, nnStar); };
3068 ensureScalars();
3069 const int hist = guessHist_;
3070 CCField v1 = guessV1_;
3071 Kokkos::deep_copy(CCExec(), r, b);
3072 removeMean(l0, r); // r = P b (the cold path's r)
3073 maxabsTo(l0, r, kGRref);
3074 if (fused) {
3075 matvecGuessDots<2>(l0, av1, v1, CCField(), r, kG11, kGb1, -1);
3076 if (hist == 2)
3077 matvecGuessDots<3>(l0, av2, x, v1, r, kG22, kGb2, kG12);
3078 } else {
3079 matvec(av1, v1);
3080 dotTo(l0, v1, av1, kG11);
3081 dotTo(l0, v1, r, kGb1);
3082 if (hist == 2) {
3083 matvec(av2, x);
3084 dotTo(l0, x, av2, kG22);
3085 dotTo(l0, v1, av2, kG12);
3086 dotTo(l0, x, r, kGb2);
3087 }
3088 }
3089 Kokkos::deep_copy(
3090 CCExec(), kgp_,
3091 Kokkos::subview(ks_, std::make_pair((int)kGRref, (int)kGRref + kGuessPacket)));
3092 CCExec().fence("peclet::flow::mg_guess_packet");
3093#ifdef PECLET_FLOW_MPI
3094 if (distributed_) { // E-dist (§6 item 2): the local partials -> global; every rank gets one c
3095 const auto t0 = std::chrono::steady_clock::now();
3096 const MPI_Comm c = l0.comm == nullptr_comm() ? comm_ : l0.comm;
3097 MPI_Allreduce(MPI_IN_PLACE, kgp_.data() + 1, kGuessPacket - 1, MPI_DOUBLE, MPI_SUM, c);
3098 MPI_Allreduce(MPI_IN_PLACE, kgp_.data(), 1, MPI_DOUBLE, MPI_MAX, c);
3099 allreduceTime_ +=
3100 std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
3101 allreduceCount_ += 2;
3102 }
3103#endif
3104 const double rref = kgp_(0), G11 = kgp_(1), G12 = kgp_(2), G22 = kgp_(3), g1 = kgp_(4),
3105 g2 = kgp_(5);
3106 double c1 = 0.0, c2 = 0.0;
3107 if (G11 > 0.0 && std::isfinite(G11)) {
3108 const double l11 = std::sqrt(G11);
3109 double l21 = 0.0, d = 0.0;
3110 if (hist == 2) {
3111 l21 = G12 / l11;
3112 d = G22 - l21 * l21;
3113 }
3114 if (hist < 2 || !(d > 1e-10 * G22)) {
3115 c1 = g1 / G11;
3116 c2 = 0.0;
3117 } else {
3118 const double y1 = g1 / l11, y2 = (g2 - l21 * y1) / std::sqrt(d);
3119 c2 = y2 / std::sqrt(d);
3120 c1 = (y1 - l21 * c2) / l11;
3121 }
3122 if (!std::isfinite(c1) || !std::isfinite(c2))
3123 c1 = c2 = 0.0;
3124 }
3125 guessC1_ = c1;
3126 guessC2_ = c2;
3127 if (c1 == 0.0 && c2 == 0.0) {
3128 Kokkos::deep_copy(CCExec(), x, 0.0); // the cold state exactly (r = P b kept)
3129 if (r0w)
3130 *r0w = rref;
3131 return rref;
3132 }
3133 {
3134 const C3 e = l0.ext;
3135 const int g = l0.g;
3136 CCField xx = x, rr = r;
3137 CCConst vv1 = v1, a1 = av1, a2 = av2;
3138 FPV ac = l0.AC;
3139 // c2 == 0 (history 1, or the Cholesky / non-finite fallback): never read v2 (0 * NaN = NaN)
3140 const bool all = hostAllFluid(l0), two = hist == 2 && c2 != 0.0;
3141 ccFor3(
3142 "peclet::flow::mg_guess_x", C3{0, 0, 0}, C3{e.x, e.y, e.z},
3143 KOKKOS_LAMBDA(int ix, int iy, int iz) {
3144 const long i = (long)ix + (long)iy * e.x + (long)iz * (long)e.x * e.y;
3145 if (ix < g || iy < g || iz < g || ix >= e.x - g || iy >= e.y - g || iz >= e.z - g) {
3146 xx(i) = 0.0; // ghosts of the guess: 0
3147 return;
3148 }
3149 const bool fl = all || ac(i) > 1e-30f;
3150 xx(i) = fl ? (two ? c1 * vv1(i) + c2 * xx(i) : c1 * vv1(i)) : 0.0;
3151 rr(i) -= two ? c1 * a1(i) + c2 * a2(i) : c1 * a1(i);
3152 });
3153 }
3154 removeMean(l0, r);
3155 if (r0w)
3156 *r0w = maxabs(l0, r);
3157 return rref;
3158 }
3159 // The E trace (debug output only: PECLET_FLOW_MG_DEBUG >= 2, the solves the PCG trace covers;
3160 // distributed it is collective and rank 0 prints):
3161 // G-E1 ||x - x0||_A <= ||x||_A, G-E2 the freshly recomputed max|P(b - A x)| / rref, G-E4 the
3162 // number of non-fluid inner cells with x0 != 0. Trace buffers only; the solve is untouched.
3164 if (guessX0_.extent(0) != x.extent(0)) {
3165 guessX0_ = CCField("peclet::flow::mg_guess_x0", x.extent(0));
3166 guessTA_ = CCField("peclet::flow::mg_guess_ta", x.extent(0));
3167 guessTB_ = CCField("peclet::flow::mg_guess_tb", x.extent(0));
3168 }
3169 Kokkos::deep_copy(CCExec(), guessX0_, x);
3170 }
3171 void guessTraceExit(Level& l0, CCField b, CCField x, double rref, double r0w, int it, int hist,
3172 const StarOverlay* star, int nStar, C3 nnStar) {
3173 auto matvec = [&](CCField y, CCField v) { guessMatvec(l0, y, v, star, nStar, nnStar); };
3174 CCField ta = guessTA_, tb = guessTB_, x0 = guessX0_, xx = x;
3175 Kokkos::parallel_for(
3176 "peclet::flow::mg_guess_trace_diff", Kokkos::RangePolicy<CCExec>(CCExec(), 0, x.extent(0)),
3177 KOKKOS_LAMBDA(std::size_t i) { ta(i) = xx(i) - x0(i); });
3178 matvec(tb, ta);
3179 const double eA2 = dot(l0, ta, tb);
3180 Kokkos::deep_copy(CCExec(), ta, x);
3181 matvec(tb, ta);
3182 const double xA2 = dot(l0, ta, tb);
3183 Kokkos::deep_copy(CCExec(), ta, b);
3184 axpy(ta, -1.0, tb);
3185 removeMean(l0, ta);
3186 const double rfin = maxabs(l0, ta);
3187 long bad = 0;
3188 {
3189 const C3 e = l0.ext;
3190 const int g = l0.g;
3191 FPV ac = l0.AC;
3192 ccReduce3(
3193 "peclet::flow::mg_guess_trace_nonfluid", C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g},
3194 KOKKOS_LAMBDA(int ix, int iy, int iz, long& k) {
3195 const long i = (long)ix + (long)iy * e.x + (long)iz * (long)e.x * e.y;
3196 if (!(ac(i) > 1e-30f) && x0(i) != 0.0)
3197 k += 1;
3198 },
3199 bad);
3200 }
3201 // E-dist (§6 item 2): collective (dot, maxabs, the matvec, this count); rank 0 prints.
3202#ifdef PECLET_FLOW_MPI
3203 if (distributed_)
3204 bad = (long)allreduce((double)bad, MPI_SUM_, l0.comm);
3205#endif
3206 if (commRank() != 0)
3207 return;
3208 printf(
3209 "[mg] guess solve %d: hist %d c1 %.17g c2 %.17g rref %.6e r0w %.6e iters %d "
3210 "eA %.6e xA %.6e eA/xA %.6e resid/rref %.6e x0_nonfluid_nonzero %ld\n",
3211 dbgSolve_ - 1, hist, guessC1_, guessC2_, rref, r0w, it, std::sqrt(std::max(eA2, 0.0)),
3212 std::sqrt(std::max(xA2, 0.0)), xA2 > 0.0 ? std::sqrt(std::max(eA2, 0.0) / xA2) : 0.0,
3213 rref > 0.0 ? rfin / rref : 0.0, bad);
3214 }
3215 // solvePCGResident's residual of the caller's guess x (no projected guess): r = b - A x, onto
3216 // the range; returns r0 = max|r|, the solve's one host read of it.
3218 const StarOverlay* star, int nStar, C3 nnStar) {
3219 if (zeroGuess_) {
3220 // H-2c (§8): the caller guarantees x0 = +0, so A x0 = +0 in every cell and
3221 // b + (-1)(+0) = b for every b (+-0 included): r = b with no matvec. The matvec's only
3222 // side effect on x, the ghost fill of the non-wrap path, is kept.
3223 if (!fusedWrapReads()) {
3224 fill(l0, x);
3225 applyOutflowGhost(l0, x);
3226 }
3227 Kokkos::deep_copy(CCExec(), r, b);
3228 } else {
3229 guessMatvec(l0, Ap, x, star, nStar, nnStar); // r = b - A x
3230 Kokkos::deep_copy(CCExec(), r, b);
3231 axpy(r, -1.0, Ap);
3232 }
3233 removeMean(l0, r); // compatibility: project rhs/residual onto the range
3234 return maxabs(l0, r); // host read (once per solve)
3235 }
3236 // An attempt's starting residual (E, §5.3). With a projected guess armed, r0 is rref = max|P b|,
3237 // the zero-guess residual, and r0w the guess's own residual (traced only); else r = b - A x
3238 // (initialResidual on the resident driver, guessResidual on the host-scalar ones) and r0w = r0.
3239 // fused: projectedGuess's fused pass. The guess trace (collective; rank 0 prints) saves x.
3241 double r0, r0w;
3242 bool traceGuess; // the guess trace is on: the attempt ends with guessTraceExit
3243 };
3245 const StarOverlay* star, int nStar, C3 nnStar, bool fused,
3246 bool resident) {
3247 Level& l0 = lv_[0];
3248 const bool guessOn = guessV1_.extent(0) > 0;
3249 const bool traceGuess = guessOn && mgDebugLevel() >= 2 && dbgSolve_ < mgDebugSolves();
3250 double r0 = 0.0, r0w = 0.0;
3251 if (guessOn && guessHist_ > 0) {
3252 r0 = projectedGuess(l0, b, x, r, Ap, z, star, nStar, nnStar, fused,
3253 traceGuess ? &r0w : nullptr);
3254 } else {
3255 r0 = resident ? initialResidual(l0, b, x, r, Ap, star, nStar, nnStar)
3256 : guessResidual(l0, b, x, r, Ap, star, nStar, nnStar);
3257 r0w = r0;
3258 }
3259 if (traceGuess)
3260 guessTraceSave(x);
3261 return StartResidual{r0, r0w, traceGuess};
3262 }
3263 // solvePCGResident's Ap = A p and p^T Ap into slot kPAp: C1's one fused pass when fuse (and no
3264 // "all"-scope mean removal), else the matvec, that mean removal and the dot.
3265 void matvecDotPAp(Level& l0, CCField Ap, CCField p, bool fuse, const StarOverlay* star, int nStar,
3266 C3 nnStar) {
3267 if (fuse && !meanRemovalAll_) {
3268 matvecDotTo(l0, Ap, p, kPAp); // C1: Ap = A p and p^T Ap in one pass (star == nullptr)
3269 } else {
3270 guessMatvec(l0, Ap, p, star, nStar, nnStar);
3271 if (meanRemovalAll_)
3272 removeMean(l0, Ap); // A preserves mean-freeness; "fine" scope trusts that
3273 dotTo(l0, p, Ap, kPAp);
3274 }
3275 }
3276 // solvePCGResident's health instrument at iteration it: |r_{k+1}^T z_k| / |r_{k+1}^T z_{k+1}|
3277 // (rzOld the former, slot kRzNew the latter), logged and, under the trace, printed.
3278 void noteHealth(double rzOld, int it, bool trace, bool f32) {
3279 const double rzNew = readSlot(kRzNew);
3280 const double ratio = rzNew != 0.0 ? std::abs(rzOld / rzNew) : 0.0;
3281 healthLog_.push_back(ratio);
3282 if (trace)
3283 printf("[mg] it %3d health |r^T z_k| / |r^T z_{k+1}| = %.3e%s\n", it + 1, ratio,
3284 f32 ? " (fp32 V-cycle)" : "");
3285 }
3286 // solvePCGResident's z = M r with r^T z into slot k: the FP32 V-cycle (scale exponent e) forms it
3287 // in its exit; the FP64 one (A5) under C4 (fuse) from its level-0 exit pass, p = z there when pz
3288 // is given (copyDotTo's fusion condition). false: no exit pass formed it (a one-level V-cycle)
3289 // -> the caller's own kernels.
3290 bool precondDotTo(bool f32, bool fuse, int e, int k, CCField z, CCField r, CCField pz) {
3291 if (f32) {
3292 precondVcycleFp32(z, r, e, k, pz);
3293 return true;
3294 }
3295 exitDot_ = ExitDot{fuse ? k : -1, pz, false};
3296 precondVcycle(z, r);
3297 const bool done = exitDot_.done;
3298 exitDot_ = ExitDot{};
3299 return done;
3300 }
3301 // solvePCGResident's first preconditioner application: z = M r, p = z and r^T z into kRz (fused
3302 // into the V-cycle's exit where it can be); returns r^T z (one host read).
3303 double firstPrecondRz(Level& l0, bool f32, bool fuse, int e, CCField z, CCField r, CCField p) {
3304 const bool copyFused = kHostMemory && fusedWrapSmooth(l0) && lv_.size() > 1;
3305 if (!precondDotTo(f32, fuse, e, kRz, z, r, copyFused ? p : CCField()))
3306 copyDotTo(l0, p, r, z, kRz); // p = z; r^T z into kRz
3307 else if (!copyFused)
3308 Kokkos::deep_copy(CCExec(), p, z);
3309 return readSlot(kRz); // host read (the initial guard)
3310 }
3311 // solvePCGResident's alpha = rz / pAp on the device, or the pAp breakdown flag. The R test hook
3312 // (dbgBrkWhich_ 1) poisons p^T Ap at iteration dbgBrkIter_ first.
3313 void residentAlpha(int it) {
3314 if (dbgBrkWhich_ == 1 && it == dbgBrkIter_)
3315 setSlot(kPAp, std::numeric_limits<double>::quiet_NaN());
3316 auto ks = ks_;
3317 const double brkPAp = kBrkPAp; // by value into the kernel
3318 Kokkos::parallel_for( // alpha = rz / pAp, or the pAp breakdown flag
3319 "mgpcg_alpha", Kokkos::RangePolicy<CCExec>(CCExec(), 0, 1), KOKKOS_LAMBDA(int) {
3320 const double pAp = ks(kPAp);
3321 if (ks(kStop) == 0.0) {
3322 if (Kokkos::isfinite(pAp) && pAp > 1e-300)
3323 ks(kAlpha) = ks(kRz) / pAp;
3324 else
3325 ks(kStop) = brkPAp;
3326 }
3327 });
3328 }
3329 // solvePCGResident's x += alpha p, r -= alpha Ap onto the range and max|r| into slot kRn, all
3330 // skipped once the stop flag is set: C2 + C3 when fuse, else the update kernel, the
3331 // stop-guarded mean removal and maxabsTo.
3332 void residentUpdate(Level& l0, CCField xx, CCField rr, CCField pp, CCField aa, bool fuse) {
3333 if (fuse) {
3334 pcgUpdateSum(l0, xx, rr, pp, aa); // C2: the update + the fluid sum of r
3335 meanSubtractMaxTo(l0, rr, kRn); // C3: the stop-guarded subtract + max|r|
3336 } else {
3337 auto ks = ks_;
3338 const std::size_t n = xx.extent(0);
3339 Kokkos::parallel_for( // x += alpha p; r -= alpha Ap (axpy's expressions)
3340 "mgpcg_update", Kokkos::RangePolicy<CCExec>(CCExec(), 0, n),
3341 KOKKOS_LAMBDA(std::size_t i) {
3342 if (ks(kStop) != 0.0)
3343 return;
3344 const double a = ks(kAlpha), na = -a;
3345 xx(i) += a * pp(i);
3346 rr(i) += na * aa(i);
3347 });
3348 removeMean(l0, rr, /*stopGuard=*/true);
3349 maxabsTo(l0, rr, kRn);
3350 }
3351 }
3352 // solvePCGResident's one host read per iteration (the packet {pAp, rn, stop, bottomFlag}) and its
3353 // exit test: a breakdown (it then names the iteration that computed it) or convergence (it then
3354 // counts this one). Returns true to leave the loop; rn is max|r|.
3355 bool residentPacketExit(int& it, double rtol, double rref, double r0, bool trace, double& rn) {
3356 Kokkos::deep_copy(CCExec(), kpk_, Kokkos::subview(ks_, std::make_pair(0, kPacket)));
3357 CCExec().fence("peclet::flow::mg_packet"); // THE read
3358 const double pAp = kpk_(0), stop = kpk_(2);
3359 rn = kpk_(1);
3360 noteBottomFlag(kpk_(3)); // a non-finite scalar in a device bottom solve
3361 if (stop == kBrkRz) { // r^T z of the previous iteration was non-finite
3362 solveFailed_ = true; // ISSUES sweep item 6: a breakdown, not a convergence
3363 --it; // report the iteration that computed it
3364 return true;
3365 }
3366 if (stop == kBrkPAp) {
3367 if (!std::isfinite(pAp))
3368 solveFailed_ = true; // ISSUES sweep item 6 (pAp <= 1e-300 is a CONVERGED direction)
3369 return true; // keep the last finite iterate
3370 }
3371 return cgConverged(it, rn, r0, rtol, rref, trace);
3372 }
3373 // solvePCGResident's z = M r with r^T z into slot kRzNew (C4: from the V-cycle's exit pass, else
3374 // dotTo), e = ilogb(rn) the FP32 V-cycle's scale; with the health instrument (rzOld = r_{k+1}^T
3375 // z_k) and the R test hook (dbgBrkWhich_ 2), which poisons r^T z at iteration dbgBrkIter_.
3376 void residentPrecondRz(Level& l0, bool f32, bool fuse, int e, CCField z, CCField r, int it,
3377 bool health, bool trace) {
3378 const double rzOld = health ? dot(l0, r, z) : 0.0; // r_{k+1}^T z_k (the instrument)
3379 if (!precondDotTo(f32, fuse, e, kRzNew, z, r, CCField())) // C4: from the exit pass
3380 dotTo(l0, r, z, kRzNew);
3381 if (health)
3382 noteHealth(rzOld, it, trace, f32);
3383 if (dbgBrkWhich_ == 2 && it == dbgBrkIter_)
3384 setSlot(kRzNew, std::numeric_limits<double>::quiet_NaN());
3385 }
3386 // solvePCGResident's beta = r^T z_new / r^T z and rz = r^T z_new on the device (or the r^T z
3387 // breakdown flag), then p = z + beta p; both skipped once the stop flag is set.
3388 void residentBetaAypx(CCField pp, CCField zz, std::size_t n) {
3389 auto ks = ks_;
3390 const double brkRz = kBrkRz; // by value into the kernel
3391 Kokkos::parallel_for( // beta = r^T z_new / r^T z; rz = r^T z_new -- or the flag
3392 "mgpcg_beta", Kokkos::RangePolicy<CCExec>(CCExec(), 0, 1), KOKKOS_LAMBDA(int) {
3393 const double rznew = ks(kRzNew);
3394 if (Kokkos::isfinite(rznew)) {
3395 ks(kBeta) = rznew / ks(kRz);
3396 ks(kRz) = rznew;
3397 } else {
3398 ks(kStop) = brkRz;
3399 }
3400 });
3401 Kokkos::parallel_for( // p = z + beta p (aypx's expression)
3402 "mgaypx", Kokkos::RangePolicy<CCExec>(CCExec(), 0, n), KOKKOS_LAMBDA(std::size_t i) {
3403 if (ks(kStop) != 0.0)
3404 return;
3405 pp(i) = zz(i) + ks(kBeta) * pp(i);
3406 });
3407 }
3409 double rtol, int pre, int post, int bottom, const StarOverlay* star,
3410 int nStar, C3 nnStar) {
3411 solveFailed_ = false; // ISSUES sweep item 6: per-solve breakdown flag
3412 lastSolveConverged_ = false; // R (§4): per attempt
3413 OverlayScope overlay(overlaySolve_, star != nullptr);
3414 pre_ = pre;
3415 post_ = post;
3416 bottom_ = bottom;
3417 ensureScalars();
3418 Level& l0 = lv_[0]; // H-2b: l0.x is not staged (no reader between or inside the solves)
3419 const bool trace = mgDebugLevel() >= 2 && dbgSolve_ < mgDebugSolves();
3420 // E (§5.3): with a projected guess r0 below is rref = max|P b|, the zero-guess residual (the
3421 // guard, the stop and the FP32 V-cycle's scale exponent read it; the host holds no other)
3422 const StartResidual s0 =
3423 startResidual(b, x, r, Ap, z, star, nStar, nnStar, hostKrylovFusion() && star == nullptr,
3424 /*resident=*/true);
3425 const double r0 = s0.r0;
3426 // X1: the stop reference, as in solvePCG's distributed loop, solveFCG and solveChebyshev: r0,
3427 // or the caller's FULL right-hand-side norm when one is set (setStopReference; only the
3428 // balanced-force projection sets it). Unset, rref IS r0: `rtol * rref` is the old test bitwise.
3429 const double rref = armStopTest(r0, rtol);
3430 int it = 0;
3431 if (trace)
3432 printf("[mg] solve %d: r0=%.6e rtol=%.1e (pre=%d post=%d bottom=%d)\n", dbgSolve_, r0, rtol,
3433 pre, post, bottom);
3434 ++dbgSolve_;
3435 const bool fuseC = hostKrylovFusion(); // C1-C4 (§6): the fused host kernels
3436 struct ExitDotScope { // C4's request never outlives this solve
3437 ExitDot& d;
3438 ~ExitDotScope() { d = ExitDot{}; }
3439 } exitDotScope{exitDot_};
3440 // D (§4.4.5): the FP32 V-cycle on an eligible solve; it takes e = ilogb(rn) inside the loop
3441 // (the packet's rn = max|r|) and e = ilogb(r0) on entry -- under E r0 is the stop reference
3442 // max|P b|, the only value the host holds, not max|r| of the guess residual: inert by the scale
3443 // covariance B(2^k r) = 2^k B(r) (G-D2 (a)) away from the FP32 range edges. It forms r^T z in
3444 // its exit.
3445 const bool f32 = beginAttemptPrecision(maxit);
3446 const bool health = trace || healthTrace_;
3447 healthLog_.clear();
3448 lastSolveConverged_ = r0 == 0.0; // R (§4): the loop is skipped on a zero residual
3449 if (r0 > 0.0 && std::isfinite(r0)) {
3450 const double rz0 = firstPrecondRz(l0, f32, fuseC, std::ilogb(r0), z, r, p); // the guard
3451 if (!std::isfinite(rz0))
3452 return failNonFiniteZ("solvePCG", l0, x, maxit);
3453 setSlot(kStop, 0.0);
3454 const std::size_t n = x.extent(0);
3455 bool exited = false;
3456 for (; it < maxit; ++it) {
3457 matvecDotPAp(l0, Ap, p, fuseC, star, nStar, nnStar);
3458 residentAlpha(it);
3459 residentUpdate(l0, x, r, p, Ap, fuseC);
3460 double rn = 0.0;
3461 if (residentPacketExit(it, rtol, rref, r0, trace, rn)) {
3462 exited = true;
3463 break;
3464 }
3465 residentPrecondRz(l0, f32, fuseC, std::ilogb(rn), z, r, it, health, trace);
3466 residentBetaAypx(p, z, n);
3467 }
3468 if (!exited && maxit > 0 && readSlot(kStop) == kBrkRz) {
3469 solveFailed_ = true; // the last iteration's r^T z was non-finite
3470 it = maxit - 1;
3471 }
3472 }
3473 removeMean(l0, x); // H-2b: in place (was the l0.x round trip; same cells, same values)
3474 if (s0.traceGuess)
3475 guessTraceExit(l0, b, x, r0, s0.r0w, it, guessHist_, star, nStar, nnStar);
3476 return it;
3477 }
3478
3479 // FLEXIBLE CG (Notay 2000 / Golub-Ye "inexact preconditioned CG"; the Polak-Ribiere form of
3480 // Axelsson's generalized CG), preconditioned by the SAME one symmetric V-cycle as solvePCG.
3481 //
3482 // The ONLY difference from solvePCG is the beta recurrence: Fletcher-Reeves
3483 // beta = r_{k+1}^T z_{k+1} / (r_k^T z_k)
3484 // is replaced by Polak-Ribiere
3485 // beta = r_{k+1}^T (z_{k+1} - z_k) / (r_k^T z_k),
3486 // at the cost of one extra stored vector (z_k) and one extra global dot per iteration. The two
3487 // forms are ALGEBRAICALLY IDENTICAL when the preconditioner is a fixed SPD operator, because
3488 // then r_{k+1} is M^{-1}A-orthogonal to z_k, i.e. r_{k+1}^T z_k = 0 exactly -- so on a healthy
3489 // problem FCG must reproduce PCG's iteration count (that equality is the sanity gate). When the
3490 // preconditioner is NOT symmetric w.r.t. the fine operator, that orthogonality is lost, the
3491 // Fletcher-Reeves numerator is contaminated by a term CG has no right to, and the iteration
3492 // stalls; Polak-Ribiere subtracts exactly that term, which is why FCG converging where PCG
3493 // stalls is a DIAGNOSIS ("the preconditioner is nonsymmetric") and not merely a fix.
3494 //
3495 // Everything else -- matvec (incl. the optional star overlay), preconditioner, mean removal,
3496 // the maxabs(r) < rtol*r0 stopping estimate, the breakdown guards, the final mean removal -- is
3497 // identical to solvePCG line for line. Keep the two in sync if either is ever changed.
3498 // Scratch: solvePCG's five level-0 fields plus `zp` (the previous preconditioned residual).
3500 int maxit, double rtol, int pre, int post, int bottom,
3501 const StarOverlay* star = nullptr, int nStar = 0, C3 nnStar = C3{0, 0, 0}) {
3502 return solveWithRestart(x, maxit, [&](int m) {
3503 return solveFCGAttempt(b, x, r, p, z, zp, Ap, m, rtol, pre, post, bottom, star, nStar,
3504 nnStar);
3505 });
3506 }
3507 // solveFCGAttempt's z = M r and r^T z; p = z too when p is given (the first application). fuse:
3508 // K4 C4, r^T z from the FP64 V-cycle's level-0 exit pass. Else the V-cycle -- FP32 with
3509 // e = ilogb(rn) (D §4.4.5; FCG keeps its own dots) or FP64 (A5) -- and dot().
3510 double fcgPrecondRz(Level& l0, bool f32, bool fuse, CCField z, CCField r, double rn, CCField p) {
3511 if (fuse) {
3512 const double rz = precondDotDist(z, r);
3513 if (p.extent(0) != 0)
3514 Kokkos::deep_copy(CCExec(), p, z);
3515 return rz;
3516 }
3517 if (f32)
3518 precondVcycleFp32(z, r, std::ilogb(rn), -1, CCField());
3519 else
3520 precondVcycle(z, r);
3521 if (p.extent(0) != 0)
3522 Kokkos::deep_copy(CCExec(), p, z);
3523 return dot(l0, r, z);
3524 }
3525 // solveFCGAttempt's DIAGNOSTIC (PECLET_FLOW_MG_DEBUG>=2): `pr` is |r_{k+1}^T z_k| /
3526 // |r_{k+1}^T z_{k+1}| -- the term Fletcher-Reeves keeps and Polak-Ribiere removes. With a
3527 // preconditioner that is symmetric w.r.t. the fine operator this is EXACTLY zero in exact
3528 // arithmetic, so a measured pr ~ 1e-14 says "the V-cycle is symmetric here (and FCG == PCG by
3529 // construction)" while pr = O(1) says "it is not" -- a direct read-out of the hypothesis, per
3530 // iteration, that needs no extra solve. The health log (§4.4.5) records it too: FCG forms this
3531 // dot anyway.
3532 void fcgNotePr(int it, double beta, double rznew, double rzcross, bool trace) {
3533 if (trace)
3534 printf("[mg] it %3d beta=%.6e pr=%.3e (|r^T z_k| / |r^T z_{k+1}|)\n", it + 1, beta,
3535 rznew != 0.0 ? std::abs(rzcross / rznew) : 0.0);
3536 if (healthTrace_) // §4.4.5: FCG forms this dot anyway
3537 healthLog_.push_back(rznew != 0.0 ? std::abs(rzcross / rznew) : 0.0);
3538 }
3539 // One flexible-CG attempt (R, §4: solveFCG's body before the restart wrapper).
3541 int maxit, double rtol, int pre, int post, int bottom,
3542 const StarOverlay* star, int nStar, C3 nnStar) {
3543 solveFailed_ = false; // ISSUES sweep item 6: per-solve breakdown flag
3544 lastSolveConverged_ = false; // R (§4): per attempt
3545 OverlayScope overlay(overlaySolve_, star != nullptr);
3546 pre_ = pre;
3547 post_ = post;
3548 bottom_ = bottom;
3549 Level& l0 = lv_[0];
3550 Kokkos::deep_copy(CCExec(), l0.x, x);
3551 // D (§4.4.5): the FP32 V-cycle on an eligible solve, e = ilogb(max|r|) (on entry ilogb(r0): the
3552 // stop reference under E, see solvePCGResident); FCG keeps its own dots
3553 const bool f32 = beginAttemptPrecision(maxit);
3554 const bool fuseC23 = distKrylovFusion(); // K4 (§5.4): C2 + C3, the same MPI calls
3555 const bool fuseC4 = fuseC23 && !f32; // C4 on the FP64 V-cycle (FP32 keeps FCG's dots)
3556 healthLog_.clear();
3557 const int dbgRank = commRank();
3558 const bool trace = mgDebugLevel() >= 2 && dbgSolve_ < mgDebugSolves() && dbgRank == 0;
3559 // E (§5.3): with a projected guess r0 is rref = max|P b| (see solvePCGResident). The guess
3560 // trace is collective (E-dist §6 item 2: every rank runs it, rank 0 prints), so it does not
3561 // take `trace`'s rank-0 restriction; single rank the two coincide.
3562 const StartResidual s0 =
3563 startResidual(b, x, r, Ap, z, star, nStar, nnStar, hostKrylovFusion() && star == nullptr,
3564 /*resident=*/false);
3565 const double r0 = s0.r0;
3566 const double rref = armStopTest(r0, rtol);
3567 int it = 0;
3568 if (trace)
3569 printf("[mg] fcg solve %d: r0=%.6e rtol=%.1e (pre=%d post=%d bottom=%d)\n", dbgSolve_, r0,
3570 rtol, pre, post, bottom);
3571 ++dbgSolve_;
3572 lastSolveConverged_ = r0 == 0.0; // R (§4): the loop is skipped on a zero residual
3573 if (r0 > 0.0 && std::isfinite(r0)) {
3574 if (f32 && distributed_) // D-dist §5.5: the exit writes inner z only; wall ghosts stay 0
3575 Kokkos::deep_copy(CCExec(), z, 0.0);
3576 double rz = fcgPrecondRz(l0, f32, fuseC4, z, r, r0, p); // p = z
3577 if (!std::isfinite(rz))
3578 return failNonFiniteZ("solveFCG", l0, x, maxit);
3579 for (; it < maxit; ++it) {
3580 const double pAp = matvecPAp(l0, Ap, p, star, nStar, nnStar);
3581 if (pApBreakdown(pAp))
3582 break;
3583 const double alpha = rz / pAp;
3584 const double rn = cgUpdate(l0, x, r, p, Ap, alpha, fuseC23);
3585 if (cgConverged(it, rn, r0, rtol, rref, trace))
3586 break;
3587 Kokkos::deep_copy(CCExec(), zp, z); // z_k, before the preconditioner overwrites it
3588 const double rznew = fcgPrecondRz(l0, f32, fuseC4, z, r, rn, CCField());
3589 const double rzcross = dot(l0, r, zp);
3590 if (!std::isfinite(rznew) || !std::isfinite(rzcross)) {
3591 solveFailed_ = true; // ISSUES sweep item 6: a breakdown, not a convergence
3592 break; // preconditioner breakdown: keep the last finite iterate
3593 }
3594 const double beta = (rznew - rzcross) / rz; // Polak-Ribiere: r^T (z_{k+1} - z_k) / r^T z
3595 fcgNotePr(it, beta, rznew, rzcross, trace);
3596 aypx(p, beta, z);
3597 rz = rznew;
3598 }
3599 }
3600 finalRemoveMean(l0, x);
3601 if (s0.traceGuess)
3602 guessTraceExit(l0, b, x, r0, s0.r0w, it, guessHist_, star, nStar, nnStar);
3603 return it;
3604 }
3605
3606 // solveBiCGStab's matvec y = A q: the binary-openness 7-point op plus the ghost-projection
3607 // overlay delta. Distributed with a g=2 staging field (h2 given): q's inner cells are staged on
3608 // the ext2 block, its 2-deep halo exchanged once, and q's g=1 halo read back from the staged
3609 // copy, so one exchange serves both the 7-point op and the overlay (applied in ghost mode).
3610 void gpMatvec(Level& l0, CCField y, CCField q, const GpOverlayReal<MReal>& ov, int nOv, C3 nn
3611#ifdef PECLET_FLOW_MPI
3612 ,
3613 CCField xg2, GridHalo<double>* h2, C3 ext2
3614#endif
3615 ) {
3616#ifdef PECLET_FLOW_MPI
3617 if (distributed_ && h2) {
3618 stageG2(l0, q, xg2, ext2); // inner cells g=1 block -> g=2 block
3619 h2->exchange(xg2); // 2-deep halo (cross-rank + periodic)
3620 unstageG2(l0, q, xg2); // whole l0 block back (fills q's g=1 halo — no 2nd exchange)
3621 applyOutflowGhost(l0, q);
3622 applyCutcellOpFace(y, CCConst(q), FPC(l0.AC), FPC(l0.AFX), FPC(l0.AFY), FPC(l0.AFZ), l0.ext,
3623 G);
3624 gpApplyDelta(y, CCConst(xg2), ov, nOv, nn, l0.ext, G, ext2, 2, /*useGhost=*/true);
3625 return;
3626 }
3627#endif
3628 fill(l0, q);
3629 applyOutflowGhost(l0, q);
3630 applyCutcellOpFace(y, CCConst(q), FPC(l0.AC), FPC(l0.AFX), FPC(l0.AFY), FPC(l0.AFZ), l0.ext, G);
3631 gpApplyDelta(y, CCConst(q), ov, nOv, nn, l0.ext, G, l0.ext, G);
3632 }
3633 // solveBiCGStab's z = M r with M one symmetric V-cycle on level 0's own rhs and x (the copying
3634 // form; precondVcycle's A5 runs in place on the caller's vectors).
3636 Level& l0 = lv_[0];
3637 Kokkos::deep_copy(CCExec(), l0.rhs, rr);
3638 Kokkos::deep_copy(CCExec(), l0.x, 0.0);
3639 vcycle(0, /*sym=*/true);
3640 Kokkos::deep_copy(CCExec(), zz, l0.x);
3641 }
3642 // solveBiCGStab's exit bookkeeping: running counts of breakdown (exit codes 1-5) and stagnation
3643 // (6) exits, and the env-gated exit trace (debug output only: PECLET_FLOW_MG_DEBUG >= 2, the
3644 // first PECLET_FLOW_MG_DEBUG_SOLVES solves, rank 0): the exit reason, r0, the last |r|inf the
3645 // stop test saw and those counts. Host integers and values the solve already computed (no extra
3646 // reduction), so the solve is unchanged with the trace on or off.
3647 void noteBicgExit(int exitCode, int it, int maxit, double r0n, double rnLast, double rtol) {
3648 if (exitCode >= 1 && exitCode <= 5)
3649 ++dbgBicgBreakdowns_;
3650 else if (exitCode == 6)
3651 ++dbgBicgStagnations_;
3652 if (mgDebugLevel() >= 2 && dbgSolve_ < mgDebugSolves() && commRank() == 0)
3653 printf(
3654 "[mg] bicgstab solve %d: exit=%d it=%d maxit=%d r0=%.6e |r|inf=%.6e rtol=%.1e "
3655 "r/r0=%.4e breakdowns=%d stagnations=%d\n",
3656 dbgSolve_, exitCode, it, maxit, r0n, rnLast, rtol, r0n > 0.0 ? rnLast / r0n : 0.0,
3657 dbgBicgBreakdowns_, dbgBicgStagnations_);
3658 }
3659 // BiCGStab preconditioned by one symmetric V-cycle, for the NONSYMMETRIC ghost-projection
3660 // operator A = (binary-openness 7-point op) + (per-row overlay delta, gpApplyDelta). The MG
3661 // hierarchy/preconditioner only ever sees the symmetric binary surrogate its levels were built
3662 // from (setOpenness); the overlay enters the fine-level matvec only. Same breakdown guards +
3663 // constant-mode (mean) removal as solvePCG, plus a stagnation guard: the nonsymmetric system's
3664 // left null vector is NOT exactly the constants, so the attainable residual has a small
3665 // compatibility floor — stop when no progress instead of burning maxit. Scratch: 7 level-0
3666 // fields from the caller. Returns the iteration count.
3667 // Distributed: the reductions/mean removal already Allreduce and the V-cycle is MPI-folded; the
3668 // fine-level matvec is the one gp-specific piece. The overlay couplings reach +/-2 but the MG
3669 // block only has a g=1 halo, so the caller passes a g=2 staging field (xg2, on its ext2 block)
3670 // + that block's halo: stage q's inner cells there, exchange the 2-deep halo once, read the g=1
3671 // halo back from the staged copy (one exchange serves both the 7-point op and the overlay), and
3672 // apply the overlay in ghost mode. Single-rank (h2 == nullptr) is byte-identical to before.
3674 CCField z, CCField z2, int maxit, double rtol, int pre, int post, int bottom,
3675 const GpOverlayReal<MReal>& ov, int nOv, C3 nn
3676#ifdef PECLET_FLOW_MPI
3677 ,
3678 CCField xg2 = CCField(), GridHalo<double>* h2 = nullptr, C3 ext2 = C3{0, 0, 0}
3679#endif
3680 ) {
3681 solveFailed_ = false; // ISSUES sweep item 6: per-solve breakdown flag
3682 OverlayScope overlay(overlaySolve_, true); // A3: the gp overlay keeps today's fills
3683 ensureFp64(); // D5 (§4.4.7): the band apply and level 0's rhs below
3684 pre_ = pre;
3685 post_ = post;
3686 bottom_ = bottom;
3687 Level& l0 = lv_[0];
3688 auto matvec = [&](CCField y, CCField q) {
3689#ifdef PECLET_FLOW_MPI
3690 gpMatvec(l0, y, q, ov, nOv, nn, xg2, h2, ext2);
3691#else
3692 gpMatvec(l0, y, q, ov, nOv, nn);
3693#endif
3694 };
3695 matvec(t, x); // r = b - A x (t as scratch)
3696 Kokkos::deep_copy(CCExec(), r, b);
3697 axpy(r, -1.0, t);
3698 removeMean(l0, r);
3699 Kokkos::deep_copy(CCExec(), rh, r); // shadow residual r^ = r_0
3700 const double r0n = maxabs(l0, r);
3701 int it = 0;
3702 // Exit reason, for the debug trace below only (values the solve computes anyway): 0 stop test
3703 // met, 1 (rh,r) breakdown, 2 (rh,v) breakdown, 3 non-finite residual, 4 (t,t) breakdown,
3704 // 5 omega breakdown, 6 compatibility-floor stagnation, 7 iteration cap.
3705 int exitCode = r0n > 0.0 ? (std::isfinite(r0n) ? 7 : 3) : 0;
3706 double rnLast = r0n;
3707 if (r0n > 0.0 && std::isfinite(r0n)) {
3708 double rho = 1.0, alpha = 1.0, omega = 1.0;
3709 double best = r0n;
3710 int lastImprove = 0;
3711 Kokkos::deep_copy(CCExec(), p, 0.0);
3712 Kokkos::deep_copy(CCExec(), v, 0.0);
3713 for (; it < maxit; ++it) {
3714 const double rhoNew = dot(l0, rh, r);
3715 if (!std::isfinite(rhoNew) || std::fabs(rhoNew) < 1e-300) {
3716 exitCode = 1;
3717 break; // (rh, r) breakdown: keep the last finite iterate
3718 }
3719 const double beta = (rhoNew / rho) * (alpha / omega);
3720 rho = rhoNew;
3721 axpy(p, -omega, v); // p = r + beta (p - omega v)
3722 aypx(p, beta, r);
3723 precondVcycleCopy(z, p);
3724 matvec(v, z);
3725 removeMean(l0, v);
3726 const double rhv = dot(l0, rh, v);
3727 if (!std::isfinite(rhv) || std::fabs(rhv) < 1e-300) {
3728 exitCode = 2;
3729 break;
3730 }
3731 alpha = rho / rhv;
3732 axpy(r, -alpha, v); // r <- s = r - alpha v
3733 removeMean(l0, r);
3734 double rn = maxabs(l0, r);
3735 rnLast = rn;
3736 if (!std::isfinite(rn)) {
3737 exitCode = 3;
3738 break;
3739 }
3740 if (rn < rtol * r0n) {
3741 axpy(x, alpha, z);
3742 ++it;
3743 exitCode = 0;
3744 break;
3745 }
3746 precondVcycleCopy(z2, r);
3747 matvec(t, z2);
3748 removeMean(l0, t);
3749 const double tt = dot(l0, t, t);
3750 if (!std::isfinite(tt) || tt < 1e-300) {
3751 axpy(x, alpha, z); // omega breakdown: take the alpha half-step and stop
3752 exitCode = 4;
3753 break;
3754 }
3755 omega = dot(l0, t, r) / tt;
3756 if (!std::isfinite(omega) || std::fabs(omega) < 1e-300) {
3757 axpy(x, alpha, z);
3758 exitCode = 5;
3759 break;
3760 }
3761 axpy(x, alpha, z);
3762 axpy(x, omega, z2);
3763 axpy(r, -omega, t);
3764 removeMean(l0, r);
3765 rn = maxabs(l0, r);
3766 rnLast = rn;
3767 if (!std::isfinite(rn)) {
3768 exitCode = 3;
3769 break;
3770 }
3771 if (rn < rtol * r0n) {
3772 ++it;
3773 exitCode = 0;
3774 break;
3775 }
3776 if (rn < 0.999 * best) {
3777 best = rn;
3778 lastImprove = it;
3779 } else if (it - lastImprove > 30) {
3780 ++it; // compatibility-floor stagnation: accept the best-so-far level
3781 exitCode = 6;
3782 break;
3783 }
3784 }
3785 }
3786 noteBicgExit(exitCode, it, maxit, r0n, rnLast, rtol);
3787 ++dbgSolve_;
3788 finalRemoveMean(l0, x);
3789 return it;
3790 }
3791
3792 public: // (public for nvcc extended-lambda rule)
3793 // Per-level V-cycle wall time (PECLET_FLOW_MG_DEBUG>=3; HOST backends only — no device
3794 // fence, so on CUDA the numbers are launch times, not kernel times). Answers "how much of
3795 // the solve is spent on the small coarse levels", i.e. whether coarse-level launch
3796 // overhead is worth chasing.
3797#ifdef PECLET_FLOW_MPI
3798
3799 // Telescope data movement (host-staged; the stage is a coarse level, i.e. small), through the
3800 // stage's core RedistributeTopology. Gather: every member's INNER cells land in the merged
3801 // block at (member origin - merged origin + g) on the group root (core's forward: a group
3802 // Gatherv). Scatter-add: the inverse (core's backward: a group Scatterv, which OVERWRITES its
3803 // landing buffer), then each member ADDS the received box into `dst`'s inner cells (prolongAdd
3804 // is additive — flow's arithmetic, not the movement's). Pure data movement, bitwise.
3805 void teleGather(const Level& lv, CCField src, CCField dst) {
3806 Telescope& T = *lv.tele;
3807 auto hs = Kokkos::create_mirror_view(src);
3808 Kokkos::deep_copy(hs, src);
3809 if (!T.root()) {
3810 T.move.forward({hs.data()}, {});
3811 return;
3812 }
3813 auto hd = Kokkos::create_mirror_view(dst);
3814 T.move.forward({hs.data()}, {hd.data()});
3815 Kokkos::deep_copy(dst, hd);
3816 }
3817 // WO-R2 outflow coefficient across a telescope point: the HIGH-side outflow coefficient of a
3818 // level lives on the first ghost index beyond the inner block along the outflow axis (a plane
3819 // teleGather's inner-only pack leaves behind). Gather that plane from the members touching the
3820 // global +face into the merged stage buffer's own ghost plane, so the coarse level coarsens its
3821 // boundary coefficient from the stage exactly as it would from a finer level in place.
3822 void teleGatherOutflowPlanes(const Level& lv) {
3823 if (!outflowCoeff_)
3824 return;
3825 CCField src[3] = {lv.ox, lv.oy, lv.oz};
3826 CCField dst[3] = {lv.tele->ox, lv.tele->oy, lv.tele->oz};
3827 for (int a = 0; a < 3; ++a)
3828 if (bc_[2 * a + 1] == 3) {
3829 if (lv.tele->repartition())
3830 teleGatherPlaneRepartition(lv, src[a], dst[a], a);
3831 else
3832 teleGatherPlane(lv, src[a], dst[a], a);
3833 }
3834 }
3835 // The same plane across a REPARTITION stage, where there are no merge groups: a source block
3836 // touching the global +face sends each target block touching it the part of its plane that lies
3837 // in the target's transverse (b, c) rectangle — the box intersections, computed from the two
3838 // replicated decompositions, exactly as core's RedistributeTopology does for the inner cells.
3839 // One MPI_Alltoallv on the level's communicator (every rank takes part; most counts are zero),
3840 // cells in (c, b) order on both sides; the target lands them on its stage buffer's own ghost
3841 // plane. Pure data movement.
3842 void teleGatherPlaneRepartition(const Level& lv, CCField src, CCField dst, int a) {
3843 Telescope& T = *lv.tele;
3844 using Blk = peclet::core::decomp::Block<3>;
3845 const int b = (a + 1) % 3, c = (a + 2) % 3;
3846 const long gd[3] = {lv.gdim.x, lv.gdim.y, lv.gdim.z};
3847 int rank = 0, np = 1;
3848 MPI_Comm_rank(T.comm.parent, &rank);
3849 MPI_Comm_size(T.comm.parent, &np);
3850 auto touches = [&](const Blk& k) { return (long)(k.origin[a] + k.size[a]) == gd[a]; };
3851 // transverse overlap [lo, hi) of two blocks on axes b and c; false when empty
3852 auto overlap = [&](const Blk& p, const Blk& q, long lo[2], long hi[2]) {
3853 const int ax[2] = {b, c};
3854 for (int e = 0; e < 2; ++e) {
3855 lo[e] = (long)std::max(p.origin[ax[e]], q.origin[ax[e]]);
3856 hi[e] = (long)std::min(p.origin[ax[e]] + p.size[ax[e]], q.origin[ax[e]] + q.size[ax[e]]);
3857 if (hi[e] <= lo[e])
3858 return false;
3859 }
3860 return true;
3861 };
3862 std::vector<int> sc((std::size_t)np, 0), sd((std::size_t)np, 0), rc((std::size_t)np, 0),
3863 rd((std::size_t)np, 0);
3864 std::vector<double> sb, rb;
3865 const Blk me = T.srcDec.block((std::size_t)rank);
3866 if (touches(me)) {
3867 const int g = lv.g;
3868 const int ext[3] = {lv.ext.x, lv.ext.y, lv.ext.z};
3869 const long st[3] = {1, (long)lv.ext.x, (long)lv.ext.x * lv.ext.y};
3870 auto hs = Kokkos::create_mirror_view(src);
3871 Kokkos::deep_copy(hs, src);
3872 const long pa = (long)(ext[a] - g) * st[a];
3873 for (std::size_t t = 0; t < T.dstDec.numBlocks(); ++t) {
3874 long lo[2], hi[2];
3875 const Blk tb = T.dstDec.block(t);
3876 if (!touches(tb) || !overlap(me, tb, lo, hi))
3877 continue;
3878 sd[t] = (int)sb.size();
3879 for (long k = lo[1]; k < hi[1]; ++k)
3880 for (long j = lo[0]; j < hi[0]; ++j)
3881 sb.push_back(hs(pa + (j - (long)me.origin[b] + g) * st[b] +
3882 (k - (long)me.origin[c] + g) * st[c]));
3883 sc[t] = (int)sb.size() - sd[t];
3884 }
3885 }
3886 const bool land = T.root() && touches(T.dstDec.block((std::size_t)rank));
3887 if (land) {
3888 const Blk tb = T.dstDec.block((std::size_t)rank);
3889 int n = 0;
3890 for (std::size_t s2 = 0; s2 < T.srcDec.numBlocks(); ++s2) {
3891 long lo[2], hi[2];
3892 const Blk sk = T.srcDec.block(s2);
3893 if (!touches(sk) || !overlap(sk, tb, lo, hi))
3894 continue;
3895 rd[s2] = n;
3896 rc[s2] = (int)((hi[0] - lo[0]) * (hi[1] - lo[1]));
3897 n += rc[s2];
3898 }
3899 rb.resize((std::size_t)n);
3900 }
3901 MPI_Alltoallv(sb.data(), sc.data(), sd.data(), MPI_DOUBLE, rb.data(), rc.data(), rd.data(),
3902 MPI_DOUBLE, T.comm.parent);
3903 if (!land)
3904 return;
3905 const Blk tb = T.dstDec.block((std::size_t)rank);
3906 const long mst[3] = {1, (long)T.mExt.x, (long)T.mExt.x * T.mExt.y};
3907 const int mext[3] = {T.mExt.x, T.mExt.y, T.mExt.z};
3908 auto hd = Kokkos::create_mirror_view(dst);
3909 Kokkos::deep_copy(hd, dst);
3910 const long pa = (long)(mext[a] - T.g) * mst[a];
3911 for (std::size_t s2 = 0; s2 < T.srcDec.numBlocks(); ++s2) {
3912 if (rc[s2] == 0)
3913 continue;
3914 long lo[2], hi[2];
3915 overlap(T.srcDec.block(s2), tb, lo, hi);
3916 const double* q = rb.data() + rd[s2];
3917 for (long k = lo[1]; k < hi[1]; ++k)
3918 for (long j = lo[0]; j < hi[0]; ++j)
3919 hd(pa + (j - (long)tb.origin[b] + T.g) * mst[b] +
3920 (k - (long)tb.origin[c] + T.g) * mst[c]) = *q++;
3921 }
3922 Kokkos::deep_copy(dst, hd);
3923 }
3924 void teleGatherPlane(const Level& lv, CCField src, CCField dst, int a) {
3925 Telescope& T = *lv.tele;
3926 const int g = lv.g, b = (a + 1) % 3, c = (a + 2) % 3;
3927 const int ext[3] = {lv.ext.x, lv.ext.y, lv.ext.z},
3928 inn[3] = {lv.inner.x, lv.inner.y, lv.inner.z};
3929 const long st[3] = {1, (long)lv.ext.x, (long)lv.ext.x * lv.ext.y};
3930 const bool mine = touchesGlobalFace(lv, 2 * a + 1);
3931 // pack my plane (ghost index ext[a]-g along a; inner ranges along b, c) if I touch the +face
3932 std::vector<double> sb;
3933 if (mine) {
3934 auto hs = Kokkos::create_mirror_view(src);
3935 Kokkos::deep_copy(hs, src);
3936 sb.resize((std::size_t)inn[b] * inn[c]);
3937 const long pa = (long)(ext[a] - g) * st[a];
3938 for (int k = 0; k < inn[c]; ++k)
3939 for (int j = 0; j < inn[b]; ++j)
3940 sb[(std::size_t)j + (std::size_t)k * inn[b]] =
3941 hs(pa + (long)(j + g) * st[b] + (long)(k + g) * st[c]);
3942 }
3943 // the root knows which members touch the face from their block boxes (replicated)
3944 std::vector<int> counts, displs;
3945 std::vector<double> rb;
3946 const int gd[3] = {lv.gdim.x, lv.gdim.y, lv.gdim.z};
3947 if (T.root()) {
3948 int disp = 0;
3949 for (int m = 0; m < T.nMembers; ++m) {
3950 const int mo[3] = {T.memO[m].x, T.memO[m].y, T.memO[m].z};
3951 const int ms[3] = {T.memS[m].x, T.memS[m].y, T.memS[m].z};
3952 const int n = (mo[a] + ms[a] == gd[a]) ? ms[b] * ms[c] : 0;
3953 counts.push_back(n);
3954 displs.push_back(disp);
3955 disp += n;
3956 }
3957 rb.resize((std::size_t)disp);
3958 }
3959 MPI_Gatherv(sb.data(), (int)sb.size(), MPI_DOUBLE, T.root() ? rb.data() : nullptr,
3960 T.root() ? counts.data() : nullptr, T.root() ? displs.data() : nullptr, MPI_DOUBLE,
3961 0, T.comm.group);
3962 if (!T.root())
3963 return;
3964 const int mext[3] = {T.mExt.x, T.mExt.y, T.mExt.z};
3965 const long mst[3] = {1, (long)T.mExt.x, (long)T.mExt.x * T.mExt.y};
3966 const int mog[3] = {T.mOg.x, T.mOg.y, T.mOg.z};
3967 auto hd = Kokkos::create_mirror_view(dst);
3968 Kokkos::deep_copy(hd, dst);
3969 const long pa = (long)(mext[a] - T.g) * mst[a];
3970 for (int m = 0; m < T.nMembers; ++m) {
3971 if (counts[m] == 0)
3972 continue;
3973 const int mo[3] = {T.memO[m].x, T.memO[m].y, T.memO[m].z};
3974 const int ms[3] = {T.memS[m].x, T.memS[m].y, T.memS[m].z};
3975 const double* q = rb.data() + displs[m];
3976 for (int k = 0; k < ms[c]; ++k)
3977 for (int j = 0; j < ms[b]; ++j)
3978 hd(pa + (long)(mo[b] - mog[b] + j + T.g) * mst[b] +
3979 (long)(mo[c] - mog[c] + k + T.g) * mst[c]) =
3980 q[(std::size_t)j + (std::size_t)k * ms[b]];
3981 }
3982 Kokkos::deep_copy(dst, hd);
3983 }
3984 void teleScatterAdd(const Level& lv, CCField src, CCField dst) {
3985 Telescope& T = *lv.tele;
3986 const int g = lv.g;
3987 if (T.root()) {
3988 auto hs = Kokkos::create_mirror_view(src);
3989 Kokkos::deep_copy(hs, src);
3990 T.move.backward({hs.data()}, {T.back.data()});
3991 } else {
3992 T.move.backward({}, {T.back.data()});
3993 }
3994 auto hd = Kokkos::create_mirror_view(dst);
3995 Kokkos::deep_copy(hd, dst);
3996 for (int k = 0; k < lv.inner.z; ++k)
3997 for (int j = 0; j < lv.inner.y; ++j)
3998 for (int i = 0; i < lv.inner.x; ++i) {
3999 const long id =
4000 (long)(i + g) + (long)(j + g) * lv.ext.x + (long)(k + g) * (long)lv.ext.x * lv.ext.y;
4001 hd(id) += T.back[(std::size_t)id];
4002 }
4003 Kokkos::deep_copy(dst, hd);
4004 }
4005#endif
4006 // A5 (§5.5): z = M r with M one symmetric V-cycle, run IN PLACE on the caller's vectors: level
4007 // 0's `rhs` and `x` are rebound to `rr` and `zz` (shallow View assignment) for the cycle and
4008 // restored after it, replacing the `rhs <- r`, `x <- 0`, `z <- x` full-field copies. Relies on
4009 // level 0 never WRITING `rhs` (only a communication-avoiding level exchanges its rhs, and those
4010 // are coarse).
4012 Level& l0 = lv_[0];
4013 assert(!l0.caOk && "A5: level 0 must not exchange (write) its rhs");
4014 struct Restore {
4015 Level& l;
4016 CCField rhs, x;
4017 ~Restore() {
4018 l.rhs = rhs;
4019 l.x = x;
4020 }
4021 } restore{l0, l0.rhs, l0.x};
4022 l0.rhs = rr;
4023 l0.x = zz;
4024 Kokkos::deep_copy(CCExec(), zz, 0.0);
4025 vcycle(0, /*sym=*/true);
4026 }
4027 void vcycle(int L, bool sym) {
4028 if (L == 0) { // D (§4.4.6): every FP64 V-cycle passes here, the FP32 one never does
4029 lastVcycleFp32_ = false;
4030 if (vprec_ == kVcycleFp32) {
4031 const char* why = fp32VcycleIneligible(true);
4032 throw std::runtime_error(
4033 std::string("set_pressure_vcycle_precision('fp32'): not eligible here: ") +
4034 (why ? why : fp32VcycleIneligible(false)));
4035 }
4036 requireDirectBottom(); // on EVERY rank, before the V-cycle's first collective
4037 ensureFp64(); // D5 (§4.4.7): its data, if the last build deferred them
4038 }
4039 if (mgDebugLevel() >= 3) {
4040 const auto t0 = std::chrono::steady_clock::now();
4041 vcycleImpl(L, sym);
4042 lvTime_.resize(lv_.size(), 0.0);
4043 lvTime_[L] += std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
4044 if (L == 0 && ++lvCycles_ % 50 == 0) {
4045 double tot = 0;
4046 for (std::size_t i = 0; i < lvTime_.size(); ++i)
4047 tot += (i + 1 < lvTime_.size() ? lvTime_[i] - lvTime_[i + 1] : lvTime_[i]);
4048 printf("[mg] level times over %d V-cycles (total %.3f s):\n", lvCycles_, tot);
4049 for (std::size_t i = 0; i < lvTime_.size(); ++i) {
4050 const double self = (i + 1 < lvTime_.size() ? lvTime_[i] - lvTime_[i + 1] : lvTime_[i]);
4051 printf("[mg] L%zu %5dx%5dx%5d self %7.3f s (%5.1f%%)\n", i, lv_[i].inner.x,
4052 lv_[i].inner.y, lv_[i].inner.z, self, 100.0 * self / (tot + 1e-30));
4053 }
4054 fflush(stdout);
4055 }
4056 return;
4057 }
4058 vcycleImpl(L, sym);
4059 }
4060 void vcycleImpl(int L, bool sym) {
4061 Level& lv = lv_[L];
4062 // The bottom is the last level THIS rank holds that is not a telescope point: a rank idling
4063 // below a telescope point ends its lv_ at that point and must take the transition branch
4064 // (gather, skip, scatter), never the bottom solve.
4065 bool isBottom = (L + 1 == (int)lv_.size());
4066#ifdef PECLET_FLOW_MPI
4067 if (lv.tele)
4068 isBottom = false;
4069#endif
4070 if (isBottom) {
4071 if (bottomSolver_ == kBottomDirect) {
4072 if (const char* why = directBottomIneligible())
4073 throw std::runtime_error(
4074 std::string("set_pressure_bottom_solver('direct'): not eligible here: ") + why);
4075 }
4076 if (agglomerateBottom()) {
4077 if (bottomSolver_ != kBottomAlgebraic && directBottomIneligible() == nullptr)
4078 directBottomSolve(); // §13: FCG + the FP32 direct factor (device, one launch)
4079 else
4081 lv); // agglomerated mesh-agnostic coarse solve (decomposition-agnostic)
4082 } else if (symVcycle_ && bottom_ > 0) {
4083 // A3.3 item 3: the palindromic smoothed bottom, a forward run then a reverse run (the
4084 // alternating colour sequence R B ... R, A-self-adjoint); 12 -> 6 + 6.
4085 smooth(lv, std::max(1, bottom_ / 2), false);
4086 smooth(lv, std::max(1, bottom_ - bottom_ / 2), true);
4087 } else
4088 smooth(lv, bottom_, false);
4089 if (meanRemovalAll_)
4090 removeMean(lv, lv.x);
4091 return;
4092 }
4093 smooth(lv, pre_, false);
4094 // Refresh the halo before the residual. The smoother exchanges BEFORE each color sweep, so on
4095 // return the ghosts are one color-update stale: the residual — and hence the restricted coarse
4096 // rhs — is wrong on the block-boundary shell. That perturbation is proportional to the block
4097 // SURFACE, so it made the V-cycle's convergence rate decomposition-dependent: fat blocks (few
4098 // ranks) needed measurably more Krylov iterations than thin ones on the SAME grid (768x640x384
4099 // genoa: 12 iters at 12-24 ranks vs 8.1 at 96; 256^3 workstation: 8/6.5/9 at np=1/8/24 -> a
4100 // flat 4.0 with the refresh). Distributed: overlap the exchange with the interior residual
4101 // (same interior/shell split as the smoother); single-rank: the periodic wrap copy.
4102 auto fullResidual = [&] {
4103 residualCutcellFace(lv.res, CCConst(lv.x), CCConst(lv.rhs), FPC(lv.AC), FPC(lv.AFX),
4104 FPC(lv.AFY), FPC(lv.AFZ), lv.ext, lv.g);
4105 };
4106#ifdef PECLET_FLOW_MPI
4107 if (distributed_) {
4108 const int g = lv.g;
4109 const int m = stencilWrap(lv); // K3 (§5.2), as in smooth()
4110 const C3 lo = boxLo(g, m), hi = boxHi(lv.ext, g, m);
4111 if (m == 7) {
4112 residualCutcellBoxFace(lv.res, CCConst(lv.x), CCConst(lv.rhs), FPC(lv.AC), FPC(lv.AFX),
4113 FPC(lv.AFY), FPC(lv.AFZ), lv.ext, lo, hi, C3{0, 0, 0}, C3{0, 0, 0},
4114 m, g);
4115 } else {
4116 GridHalo<double>& h = stencilHalo(lv);
4117 h.exchangeBegin(lv.x);
4118 residualCutcellBoxFace(lv.res, CCConst(lv.x), CCConst(lv.rhs), FPC(lv.AC), FPC(lv.AFX),
4119 FPC(lv.AFY), FPC(lv.AFZ), lv.ext, lo, hi, C3{0, 0, 0}, C3{0, 0, 0},
4120 m, g);
4121 h.exchangeEnd(lv.x);
4122 applyOutflowGhost(lv, lv.x, g);
4123 residualCutcellBoxFace(lv.res, CCConst(lv.x), CCConst(lv.rhs), FPC(lv.AC), FPC(lv.AFX),
4124 FPC(lv.AFY), FPC(lv.AFZ), lv.ext, C3{g, g, g},
4125 C3{lv.ext.x - g, lv.ext.y - g, lv.ext.z - g}, lo, hi, m, g);
4126 }
4127 } else
4128#endif
4129 {
4130 if (fusedWrapReads()) { // A3: the residual reads the periodic wrap directly, no fill
4131 residualCutcellFaceWrap(lv.res, CCConst(lv.x), CCConst(lv.rhs), FPC(lv.AC), FPC(lv.AFX),
4132 FPC(lv.AFY), FPC(lv.AFZ), lv.ext, lv.inner, lv.g);
4133 } else {
4134 fill(lv, lv.x); // single-rank: the periodic wrap copy
4135 applyOutflowGhost(lv, lv.x, lv.g);
4136 fullResidual();
4137 }
4138 }
4139#ifdef PECLET_FLOW_MPI
4140 if (lv.tele) {
4141 teleTransition(L, sym, lv.res, lv.x);
4142 } else
4143#endif
4144 {
4145 Level& cs = lv_[L + 1];
4146 if (!distributed_) { // A5: the restriction zeroes cs.x's inner cells itself
4147 restrictAvgZeroX(cs.rhs, cs.x, CCConst(lv.res), cs.ext, lv.ext, cs.g, lv.g, cs.inner,
4148 lv.ratio);
4149 } else {
4150 restrictAvg(cs.rhs, CCConst(lv.res), cs.ext, lv.ext, cs.g, lv.g, cs.inner, lv.ratio);
4151 Kokkos::deep_copy(CCExec(), cs.x, 0.0);
4152 }
4153 vcycle(L + 1, sym);
4154 if (symVcycle_) {
4155 // A3.3 item 2: P = c R^T reads no coarse ghost, so no refresh (every consumer of cs.x's
4156 // ghosts fills, wrap-reads or overwrites them first: the A5 contract).
4157 prolongConstAdd(lv.x, CCConst(cs.x), lv.ext, cs.ext, lv.g, cs.g, lv.inner, lv.ratio);
4158 } else {
4159 fill(cs, cs.x);
4160 applyOutflowGhost(cs, cs.x, cs.g);
4161 // The trilinear prolongation reads the coarse ghost with weight 1/4 regardless of
4162 // openness, so a domain-BC face needs its real ghost policy here (Dirichlet 0 above,
4163 // Neumann zero-gradient below) instead of the periodic wrap fill() just wrote. See
4164 // applyNeumannGhost.
4165 applyNeumannGhost(cs, cs.x, cs.g);
4166 prolongAdd(lv.x, CCConst(cs.x), lv.ext, cs.ext, lv.g, cs.g, lv.inner, lv.ratio);
4167 }
4168 }
4169 smooth(lv, post_, /*reverse=*/sym);
4170 if (L == 0 && exitDot_.k >= 0) { // C4: the exit subtract also forms r^T z (solvePCGResident)
4172 exitDot_.done = true;
4173 return;
4174 }
4175 if (L == 0 && exitDotDist_.on) { // K4 C4: the distributed exit also forms the local r^T z
4176 exitDotDist_.local = removeMeanDotDist(lv);
4177 exitDotDist_.done = true;
4178 return;
4179 }
4180 if (meanRemovalAll_ || L == 0)
4181 removeMean(lv, lv.x);
4182 }
4183#ifdef PECLET_FLOW_MPI
4184 // Telescoped transition: the residual `src` goes DOWN at this level's own resolution onto the
4185 // group root (the merged block is coarsenable; this rank's block is not), the roots restrict /
4186 // recurse / prolong on the sub-communicator, and the correction comes back the same way, ADDED
4187 // into `target`. vcycleImpl passes (lv.res, lv.x); the distributed FP32 V-cycle (WO-D2b1) its
4188 // FP64 copy of the FP32 residual and a zeroed FP64 correction (design
4189 // doc/vof_projection_distributed_design.md §5.6).
4190 void teleTransition(int L, bool sym, CCField src, CCField target) {
4191 Level& lv = lv_[L];
4192 Telescope& T = *lv.tele;
4193 teleGather(lv, src, T.res);
4194 if (T.root()) {
4195 Level& cs = lv_[L + 1];
4196 restrictAvg(cs.rhs, CCConst(T.res), cs.ext, T.mExt, cs.g, T.g, cs.inner, lv.ratio);
4197 Kokkos::deep_copy(CCExec(), cs.x, 0.0);
4198 vcycle(L + 1, sym);
4199 if (symVcycle_) { // A3.3 item 2: the constant form, no coarse-ghost refresh
4200 Kokkos::deep_copy(CCExec(), T.x, 0.0);
4201 prolongConstAdd(T.x, CCConst(cs.x), T.mExt, cs.ext, T.g, cs.g, T.mInner, lv.ratio);
4202 } else {
4203 fill(cs, cs.x);
4204 applyOutflowGhost(cs, cs.x, cs.g);
4205 applyNeumannGhost(cs, cs.x, cs.g);
4206 Kokkos::deep_copy(CCExec(), T.x, 0.0);
4207 prolongAdd(T.x, CCConst(cs.x), T.mExt, cs.ext, T.g, cs.g, T.mInner, lv.ratio);
4208 }
4209 }
4210 teleScatterAdd(lv, T.x, target);
4211 }
4212#endif
4213 // Communication-avoiding smoothing on this level? Needs the width-2 topology (caOk), and the
4214 // periodic/IBM operator — with domain BCs the ring rows would need post-BC ghost openness the
4215 // exchange does not deliver, so those keep the per-colour exchange.
4216 bool caSmooth(const Level& lv) const { return distributed_ && lv.caOk && !hasBC_; }
4217 // K3 (doc/vof_distributed_host_comm_design.md §5.2): the overlapped box passes' interior box
4218 // [boxLo, boxHi) -- one cell in from the ghosts, except on a wrap axis (bit a of m), which it
4219 // spans whole, [g, ext_a - g), so that axis contributes no shell. m = 0: today's box.
4220 static C3 boxLo(int g, int m) {
4221 return {(m & 1) ? g : g + 1, (m & 2) ? g : g + 1, (m & 4) ? g : g + 1};
4222 }
4223 static C3 boxHi(C3 e, int g, int m) {
4224 return {(m & 1) ? e.x - g : e.x - g - 1, (m & 2) ? e.y - g : e.y - g - 1,
4225 (m & 4) ? e.z - g : e.z - g - 1};
4226 }
4227#ifdef PECLET_FLOW_MPI
4228 // K3 (§5.2): a distributed stencil exchange runs on the faces-only `sdev` (`sdevf`) with the
4229 // level's wrap axes read in-kernel, except while the solve carries an overlay (condition 4) or
4230 // the test hook debugSetStencilHaloOff is set: then the full `dev` (`devf`) and wrapMask = 0,
4231 // today's code.
4232 bool stencilHaloOn(const Level& lv) const {
4233 return lv.sdev && !overlaySolve_ && !stencilHaloOff_;
4234 }
4235 int stencilWrap(const Level& lv) const { return stencilHaloOn(lv) ? lv.wrapAxes : 0; }
4236 GridHalo<double>& stencilHalo(Level& lv) { return stencilHaloOn(lv) ? *lv.sdev : *lv.dev; }
4237 GridHalo<VReal>& stencilHaloF(Level& lv) {
4238 return stencilHaloOn(lv) && lv.sdevf ? *lv.sdevf : *lv.devf;
4239 }
4240#endif
4241 // A3 (§5.4) eligibility of the fused periodic-wrap reads: single rank, no outflow face (whose
4242 // Dirichlet ghost is not a copy), and no overlay on the current solve (the star /
4243 // ghost-projection paths keep today's fills). The smoother additionally needs every inner
4244 // dimension even (see cutcellSmoothColorFaceWrap); the read-only residual and matvec need no
4245 // parity.
4246 bool fusedWrapReads() const { return !distributed_ && !hasOutflow_ && !overlaySolve_; }
4247 bool fusedWrapSmooth(const Level& lv) const {
4248 return fusedWrapReads() && lv.inner.x % 2 == 0 && lv.inner.y % 2 == 0 && lv.inner.z % 2 == 0;
4249 }
4250 // --- D: the FP32 V-cycle preconditioner (doc/vof_projection_cost_design.md §4) -------------
4251 // The V-cycle precision mode (§4.4.6): 'fp64' (the default); 'fp32' = FP32 or a raise naming the
4252 // failed condition; 'auto' = FP32 where fp32VcycleIneligible() is null, else FP64, on a device
4253 // backend; 'fp64' on a host backend (doc/vof_projection_distributed_design.md WO-A). FP32 ('fp32'
4254 // and 'auto') is opt-in by USER ruling 2026-10-15: it is single-rank only, so as a default it
4255 // would break the serial <-> np=1 bit-exactness.
4256 enum : int { kVcycleAuto = 0, kVcycleFp64 = 1, kVcycleFp32 = 2 };
4257 // R (doc/vof_projection_distributed_design.md §4): the precision the mode resolves to now.
4258 // 'auto' latched to FP64 by a restart (fp32Latched_) is 'fp64' until setVcyclePrecision re-arms
4259 // it, so the FP32 build, the D5 deferral and the eligibility all follow the latch. WO-A: 'auto'
4260 // is FP32-where-eligible on DEVICE backends only; on a host backend it is 'fp64' (the host gain,
4261 // 0.92-0.95 of the projection, is short of the 0.88 rule). Forced 'fp32' runs on every backend.
4262 int effectiveVprec() const {
4263 return (vprec_ == kVcycleAuto && (fp32Latched_ || kHostMemory)) ? (int)kVcycleFp64 : vprec_;
4264 }
4265 bool fp32Mode() const { return effectiveVprec() != kVcycleFp64; }
4266 // Can this configuration be eligible (§4.4.1), as far as the operator build knows? Every
4267 // condition of fp32VcycleIneligible that does not depend on the solve (the driver, an overlay)
4268 // or on the weights themselves: single rank, no outflow face, >= 2 levels, even inner dimensions
4269 // on every non-bottom level, a double outer operator, the mean-removal scope 'fine'.
4270 bool fp32Carriable() const {
4271#ifdef PECLET_FLOW_MPI
4272 if (distributed_) { // D-dist (§5.2): the levels 0 .. fp32Last_, even GLOBAL inner dimensions
4273 if (hasOutflow_ || fp32Last_ < 0 || meanRemovalAll_)
4274 return false;
4275 if (!(exactResidual_ || std::is_same_v<MReal, double>))
4276 return false;
4277 for (int L = 0; L <= fp32Last_; ++L) {
4278 const C3 gi = lv_[L].gdim; // the level's global inner dimensions (globalInner, §5.2)
4279 if (gi.x % 2 != 0 || gi.y % 2 != 0 || gi.z % 2 != 0)
4280 return false;
4281 }
4282 return true;
4283 }
4284#endif
4285 if (distributed_ || hasOutflow_ || lv_.size() < 2 || meanRemovalAll_)
4286 return false;
4287 if (!(exactResidual_ || std::is_same_v<MReal, double>))
4288 return false;
4289 for (std::size_t L = 0; L + 1 < lv_.size(); ++L) {
4290 const C3 in = lv_[L].inner;
4291 if (in.x % 2 != 0 || in.y % 2 != 0 || in.z % 2 != 0)
4292 return false;
4293 }
4294 return true;
4295 }
4296 // Does level L carry the FP32 data (§4.4.2)? The mode is 'fp32' or 'auto', the configuration can
4297 // be eligible (fp32Carriable) and L is a non-bottom level -- so 'fp64' builds no FP32 data and
4298 // runs no face-range check. Allocates the level's six FP32 arrays (zero) on first use; a level
4299 // that does not carry them is marked stale (wOk = false).
4300 bool fp32Build(int L) {
4301 Level& lv = lv_[L];
4302 // distributed (§5.2): the levels 0 .. fp32Last_ carry (FP64 below the first telescope point)
4303 const bool beyond = distributed_ ? L > fp32Last_ : L + 1 >= (int)lv_.size();
4304 if (!fp32Mode() || beyond || !fp32Carriable()) {
4305 lv.wOk = false;
4306 return false;
4307 }
4308 if (lv.WX.extent(0) != lv.n) {
4309 lv.WX = Kokkos::View<VReal*, CCMem>("peclet::flow::mg_wx", lv.n);
4310 lv.WY = Kokkos::View<VReal*, CCMem>("peclet::flow::mg_wy", lv.n);
4311 lv.WZ = Kokkos::View<VReal*, CCMem>("peclet::flow::mg_wz", lv.n);
4312 lv.xf = Kokkos::View<VReal*, CCMem>("peclet::flow::mg_xf", lv.n);
4313 lv.rhsf = Kokkos::View<VReal*, CCMem>("peclet::flow::mg_rhsf", lv.n);
4314 lv.resf = Kokkos::View<VReal*, CCMem>("peclet::flow::mg_resf", lv.n);
4315 }
4316 if (lv.lineAxis >= 0 && lv.lncf.extent(0) != lv.n) { // A2.4: the FP32 line scratch
4317 lv.lncf = Kokkos::View<VReal*, CCMem>("peclet::flow::mg_line_f", lv.n);
4318 lv.lnyf = Kokkos::View<VReal*, CCMem>("peclet::flow::mg_line_f", lv.n);
4319 lv.lnzf = Kokkos::View<VReal*, CCMem>("peclet::flow::mg_line_f", lv.n);
4320 }
4321#ifdef PECLET_FLOW_MPI
4322 // §5.1: the FP32 ghost exchange on the level's existing topology (same g, same neighbours).
4323 // Created inside the collective operator build on a global decision.
4324 if (distributed_ && !lv.devf) {
4325 lv.devf = std::make_shared<GridHalo<VReal>>();
4326 lv.devf->init(*lv.halo);
4327 lv.devf->setLabel("mg L" + std::to_string(L) + " g" + std::to_string(lv.g) + " f32");
4328 }
4329 if (distributed_ && !lv.sdevf && lv.shalo) { // K3 (§5.2): the stencil halo's FP32 twin
4330 lv.sdevf = std::make_shared<GridHalo<VReal>>();
4331 lv.sdevf->init(*lv.shalo);
4332 lv.sdevf->setLabel("mg L" + std::to_string(L) + " g" + std::to_string(lv.g) + " f32 stencil");
4333 }
4334 if (distributed_ && lv.tele && L == fp32Last_ && lv.tcorr.extent(0) != lv.n)
4335 lv.tcorr = CCField("peclet::flow::mg_tcorr", lv.n); // §5.1 (WO-D2b1)
4336#endif
4337 return true;
4338 }
4339 // D5 (doc/vof_projection_cost_design.md §4.4.7): a level's FP64 V-cycle data -- x, rhs, res
4340 // and the face form AC, AFX, AFY, AFZ -- allocated (zero) where not yet allocated at the level's
4341 // size. Level 0's x and AC come from init (every precision reads them); level 0's x and rhs are
4342 // rebound to the caller's vectors while an A5 V-cycle runs (then they have the size).
4343 void allocFp64(Level& v) {
4344 const auto need = [&v](const auto& f) { return f.extent(0) != v.n; };
4345 if (need(v.x))
4346 v.x = CCField("mg_x", v.n);
4347 if (need(v.rhs))
4348 v.rhs = CCField("mg_rhs", v.n);
4349 if (need(v.res))
4350 v.res = CCField("mg_res", v.n);
4351 for (FPV* p : {&v.AC, &v.AFX, &v.AFY, &v.AFZ})
4352 if (need(*p))
4353 *p = FPV("mg_A", v.n);
4354 allocLine(v);
4355 }
4356 // A2.4: the FP64 line-smoother scratch of a triggered level, with the level's FP64 data.
4357 static void allocLine(Level& v) {
4358 if (v.lineAxis < 0)
4359 return;
4360 for (CCField* p : {&v.lnc, &v.lny, &v.lnz})
4361 if (p->extent(0) != v.n)
4362 *p = CCField("mg_line", v.n);
4363 }
4364 // D5: may an operator build leave out the non-bottom levels' FP64 V-cycle data? When the FP32
4365 // V-cycle data are built (fp32Build's conditions) and the outer operator is exact (the level-0
4366 // apply reads the openness, not AFX): then only an ineligible solve's FP64 V-cycle, a non-exact
4367 // level-0 apply or BiCGStab reads them, and ensureFp64 builds them for that reader.
4368 bool fp64Deferrable() const {
4369 return fp32Mode() && exactResidual_ && fp32Carriable() && !distributed_; // §5.2: not D5 dist
4370 }
4371 // Finding 5 of the C0/D/G review: the face-range check of each carrying level reduces into a
4372 // device flag (wBad_(L)), not a host scalar, so an operator build never blocks; the flags are
4373 // read back once (one copy for all levels) by the first eligibility check after a build.
4374 // fp32RangeFlag(L): zero level L's flag (asynchronously, on the build's execution space) and
4375 // return it for the build kernel.
4376 int* fp32RangeFlag(int L) {
4377 if (wBad_.extent(0) != lv_.size()) {
4378 wBad_ = Kokkos::View<int*, CCMem>("peclet::flow::mg_wbad", lv_.size());
4379 wBadHost_ = Kokkos::View<int*, PinnedHost>("peclet::flow::mg_wbad_host", lv_.size());
4380 }
4381 Kokkos::deep_copy(CCExec(), Kokkos::subview(wBad_, L), 0);
4382 wBadStale_ = true;
4383 return wBad_.data() + L;
4384 }
4385 // Level L's FP32 weights are built from the current openness and passed the face-range check.
4386 bool fp32WeightsOk(int L) const {
4387#ifdef PECLET_FLOW_MPI
4388 // §5.2: distributed, the read-back is followed by an Allreduce(MAX) of the flags of the
4389 // carrying levels 0 .. fp32Last_ (every rank holds those, so the count agrees) -- collective,
4390 // before any per-level return (+1 Allreduce per operator build).
4391 if (distributed_ && wBadStale_) {
4392 Kokkos::deep_copy(CCExec(), wBadHost_, wBad_);
4393 CCExec().fence("peclet::flow::mg_wbad_read");
4394 wBadStale_ = false;
4395 if (fp32Last_ >= 0) {
4396 if (wBad_.extent(0) < (std::size_t)(fp32Last_ + 1))
4397 throw std::logic_error(
4398 "CutcellMG::fp32WeightsOk: the range flags do not cover levels 0 .. fp32Last_");
4399 MPI_Allreduce(MPI_IN_PLACE, wBadHost_.data(), fp32Last_ + 1, MPI_INT, MPI_MAX, comm_);
4400 }
4401 }
4402#endif
4403 if (!lv_[L].wOk)
4404 return false;
4405 if (wBadStale_) {
4406 Kokkos::deep_copy(CCExec(), wBadHost_, wBad_); // the one read-back
4407 CCExec().fence("peclet::flow::mg_wbad_read"); // (fences the builds: all on CCExec)
4408 wBadStale_ = false;
4409 }
4410 return wBadHost_(L) == 0;
4411 }
4412 // A setter changed an input of fp32Carriable or fp64Deferrable (was*: their values before):
4413 // release the FP64 V-cycle data if the deferral turned on (D5), rebuild the FP32 weights from
4414 // the stored openness if carriability changed (a level that no longer carries is marked stale).
4415 void fp32Reconfigure(bool wasCarriable, bool wasDeferrable) {
4416 if (!wasDeferrable && fp64Deferrable())
4417 releaseFp64();
4418 if (wasCarriable != fp32Carriable())
4420 }
4421 // D5: before any reader of the non-bottom FP64 V-cycle data. Allocates what is missing, and
4422 // when the last operator build deferred them builds them from the stored level openness with
4423 // the build setOpenness would have used (same kernel, same operands: bitwise the eager data).
4424 // Once allocated they stay (an alternating FP32 / FP64 workload does not re-allocate per step).
4425 void ensureFp64() {
4426 for (std::size_t L = 0; L + 1 < lv_.size(); ++L)
4427 allocFp64(lv_[L]);
4428 if (!fp64Stale_)
4429 return;
4430 fp64Stale_ = false;
4431 for (int L = 0; L + 1 < (int)lv_.size(); ++L) {
4432 Level& lv = lv_[L];
4433 const double sx = 1.0 / (double)(lv.cfac.x * lv.cfac.x),
4434 sy = 1.0 / (double)(lv.cfac.y * lv.cfac.y),
4435 sz = 1.0 / (double)(lv.cfac.z * lv.cfac.z);
4436 if (fp32Build(L)) {
4437 buildCutcellOpFaceFp32(lv.AC, lv.AFX, lv.AFY, lv.AFZ, lv.WX, lv.WY, lv.WZ, CCConst(lv.ox),
4438 CCConst(lv.oy), CCConst(lv.oz), lv.ext, lv.g, gfx_ * sx, gfy_ * sy,
4439 gfz_ * sz, kOpFp64Full, fp32RangeFlag(L));
4440 lv.wOk = true;
4441 } else
4442 buildCutcellOpFace(lv.AC, lv.AFX, lv.AFY, lv.AFZ, CCConst(lv.ox), CCConst(lv.oy),
4443 CCConst(lv.oz), lv.ext, lv.g, gfx_ * sx, gfy_ * sy, gfz_ * sz);
4444 noteFluidCells(lv);
4446 }
4447 }
4448 // D5: release of the non-bottom levels' FP64 V-cycle data when a setter (the V-cycle precision,
4449 // the exact residual) turns the deferral on (level 0 keeps x and AC; ensureFp64 rebuilds the
4450 // rest on demand). The flow solver builds its first operator before enable_vof turns the exact
4451 // outer on, so without this the eagerly built data would stay allocated.
4453 for (std::size_t L = 0; L + 1 < lv_.size(); ++L) {
4454 Level& v = lv_[L];
4455 v.rhs = CCField();
4456 v.res = CCField();
4457 v.AFX = FPV();
4458 v.AFY = FPV();
4459 v.AFZ = FPV();
4460 v.lnc = CCField(); // A2.4 scratch follows the level's FP64 data (allocFp64 rebuilds it)
4461 v.lny = CCField();
4462 v.lnz = CCField();
4463 if (L > 0) {
4464 v.x = CCField();
4465 v.AC = FPV();
4466 v.nFluid = -1;
4467 v.allFluid = false;
4468 v.nFluidDevValid = false;
4469 }
4470 }
4471 fp64Stale_ = opBuilt_;
4472 }
4473 // The FP32 weights of every carrying level from the STORED level openness (the setter's
4474 // rebuild; setOpenness builds them in its own kernel). Same operands as setOpenness: level L's
4475 // metric is gf * (1 / cfac^2), which is gf itself on level 0.
4477 if (!opBuilt_)
4478 return; // the next setOpenness builds them
4479 for (int L = 0; L < (int)lv_.size(); ++L) {
4480 Level& lv = lv_[L];
4481 if (!fp32Build(L))
4482 continue;
4483 const double sx = 1.0 / (double)(lv.cfac.x * lv.cfac.x),
4484 sy = 1.0 / (double)(lv.cfac.y * lv.cfac.y),
4485 sz = 1.0 / (double)(lv.cfac.z * lv.cfac.z);
4486 buildCutcellOpFaceFp32(lv.AC, lv.AFX, lv.AFY, lv.AFZ, lv.WX, lv.WY, lv.WZ, CCConst(lv.ox),
4487 CCConst(lv.oy), CCConst(lv.oz), lv.ext, lv.g, gfx_ * sx, gfy_ * sy,
4488 gfz_ * sz, kOpFp64None, fp32RangeFlag(L));
4489 lv.wOk = true;
4490 }
4491#ifndef NDEBUG
4493#endif
4494 }
4495 // §4.4.1, §4.4.6: does this solve run the FP32 V-cycle? Evaluated once per solve by
4496 // solvePCGResident and solveFCG; 'fp32' raises naming the failed condition where ineligible,
4497 // 'auto' runs the FP64 V-cycle there.
4499 if (!fp32Mode())
4500 return false;
4501 if (const char* why = fp32VcycleIneligible(true)) {
4502 if (vprec_ == kVcycleFp32)
4503 throw std::runtime_error(
4504 std::string("set_pressure_vcycle_precision('fp32'): not eligible here: ") + why);
4505 return false;
4506 }
4507 return true;
4508 }
4509 // §4.4.5 health instrument: |r_{k+1}^T z_k| / |r_{k+1}^T z_{k+1}| per iteration of the
4510 // single-rank PCG / FCG, formed (one extra dot) only while tracing (PECLET_FLOW_MG_DEBUG >= 2,
4511 // printed) or under this test hook (recorded, healthLog(): the last solve's ratios).
4512 void setHealthTrace(bool on) { healthTrace_ = on; }
4513 const std::vector<double>& healthLog() const { return healthLog_; }
4514 // §4.4.4: one FP32 V-cycle z = M r on an eligible solve (the caller checked
4515 // fp32VcycleIneligible). e = ilogb(max|r|) of the vector being preconditioned: the input is
4516 // scaled by 2^-e and the output by 2^e, both exact. k >= 0: r^T z over the fluid cells into slot
4517 // k (and p = z when p is allocated) in the exit pass; k < 0: no dot. z's ghosts are not written
4518 // (the A3 wrap paths never read them). Uses the schedule (pre_, post_, bottom_) of the driver.
4519 void precondVcycleFp32(CCField zz, CCField rr, int e, int k, CCField p) {
4520 Level& l0 = lv_[0];
4521 requireDirectBottom(); // on EVERY rank, before the V-cycle's first collective
4522 ensureScalars();
4523 // 1. entry: rhsf = fl32(2^-e r); the first pre-smooth colour pass from x = 0 (colour 0)
4524 entryFp32(l0.xf, l0.rhsf, CCConst(rr), VConst(l0.WX), VConst(l0.WY), VConst(l0.WZ),
4525 std::ldexp(1.0, -e), l0.ext, parityOg(l0), l0.g, /*color=*/0, pre_ > 0);
4526#ifdef PECLET_FLOW_MPI
4527 if (distributed_)
4528 vcycleFp32Dist(0, /*sym=*/true); // D-dist (doc/vof_projection_distributed_design.md §5.4)
4529 else
4530#endif
4531 vcycleFp32Impl(0, /*sym=*/true); // 2., 3.
4532 double s = std::ldexp(1.0, e);
4533 if (fp32FaultKind_ == 1 && ++fp32FaultCount_ == fp32FaultAt_)
4534 s = std::numeric_limits<double>::quiet_NaN(); // R test hook (debugSetFp32Fault)
4535 exitFp32(l0, zz, rr, s, k, p); // 4.
4536 }
4537 // The red-black sweeps of smooth() on the FP32 data (wrap reads; every non-bottom level is
4538 // fusedWrapSmooth by eligibility). skipFirst: the entry pass already did the first colour.
4539 void smoothFp32(Level& lv, int sweeps, bool reverse, bool skipFirst) {
4540 const C3 og = parityOg(lv);
4541 const bool line = lineRelaxOn(lv); // A2.4: column colours on a triggered level
4542 for (int k = 0; k < sweeps; ++k)
4543 for (int s = 0; s < 2; ++s) {
4544 if (skipFirst) {
4545 skipFirst = false;
4546 continue;
4547 }
4548 const int color = reverse ? (1 - s) : s;
4549 if (line) {
4550 lineSmoothColorFp32(lv, lv.lineAxis, color);
4551 continue;
4552 }
4553 cutcellSmoothColorFp32Wrap(lv.xf, VConst(lv.rhsf), VConst(lv.WX), VConst(lv.WY),
4554 VConst(lv.WZ), lv.ext, lv.inner, og, lv.g, color);
4555 }
4556 }
4557 // §4.4.4 item 2 (and 3 at the bottom interface): vcycleImpl's single-rank schedule on the FP32
4558 // data of level L < bottom.
4559 void vcycleFp32Impl(int L, bool sym) {
4560 Level& lv = lv_[L];
4561 smoothFp32(lv, pre_, false, /*skipFirst=*/L == 0 && pre_ > 0);
4562 residualFp32Wrap(lv.resf, VConst(lv.xf), VConst(lv.rhsf), VConst(lv.WX), VConst(lv.WY),
4563 VConst(lv.WZ), lv.ext, lv.inner, lv.g);
4564 Level& cs = lv_[L + 1];
4565 if (L + 2 == (int)lv_.size()) { // the bottom: its FP64 x, rhs and engine, as today
4566 restrictFp32ToDZeroX(cs.rhs, cs.x, VConst(lv.resf), cs.ext, lv.ext, cs.g, lv.g, cs.inner,
4567 lv.ratio);
4568 vcycle(L + 1, sym);
4569 if (symVcycle_) { // A3.3 item 2: the constant form, no coarse-ghost refresh
4570 prolongConstFp32FromD(lv.xf, CCConst(cs.x), lv.ext, cs.ext, lv.g, cs.g, lv.inner, lv.ratio);
4571 } else {
4572 fill(cs, cs.x);
4573 applyOutflowGhost(cs, cs.x, cs.g);
4574 applyNeumannGhost(cs, cs.x, cs.g);
4575 prolongFp32FromD(lv.xf, CCConst(cs.x), lv.ext, cs.ext, lv.g, cs.g, lv.inner, lv.ratio);
4576 }
4577 } else {
4578 restrictFp32ZeroX(cs.rhsf, cs.xf, VConst(lv.resf), cs.ext, lv.ext, cs.g, lv.g, cs.inner,
4579 lv.ratio);
4580 vcycleFp32Impl(L + 1, sym);
4581 if (symVcycle_) {
4582 prolongConstFp32(lv.xf, VConst(cs.xf), lv.ext, cs.ext, lv.g, cs.g, lv.inner, lv.ratio);
4583 } else {
4584 fillWrap(cs, cs.xf); // fill()'s single-rank periodic copy (no outflow face: eligibility)
4585 applyNeumannGhost(cs, cs.xf, cs.g);
4586 prolongFp32(lv.xf, VConst(cs.xf), lv.ext, cs.ext, lv.g, cs.g, lv.inner, lv.ratio);
4587 }
4588 }
4589 smoothFp32(lv, post_, /*reverse=*/sym, false);
4590 }
4591#ifdef PECLET_FLOW_MPI
4592 // D-dist (doc/vof_projection_distributed_design.md §5.4, mirror rule §2): the distributed branch
4593 // of vcycleImpl / smooth transcribed op for op on the FP32 data -- each FP64 box kernel replaced
4594 // by its FP32 launch form (the single-rank FP32 cell bodies), each lv.dev exchange by lv.devf on
4595 // the FP32 field, every zeroing, fill, Neumann ghost and overlap split at its position. No
4596 // outflow face (eligibility), so applyOutflowGhost on an FP32 field has no counterpart. Levels
4597 // 0 .. fp32Last_: the last non-bottom level, or the first telescope point, whose transition
4598 // runs in FP64 (fp32ToDouble of the residual, teleTransition into tcorr, fp32AddDouble).
4599 void vcycleFp32Dist(int L, bool sym) {
4600 Level& lv = lv_[L];
4601 smoothFp32Dist(lv, pre_, false, /*skipFirst=*/L == 0 && pre_ > 0);
4602 residualFp32Dist(lv);
4603 if (lv.tele) { // L == fp32Last_ (WO-D2b1): FP64 from the first telescope point down
4604 fp32ToDouble(lv.res, VConst(lv.resf), lv.ext);
4605 Kokkos::deep_copy(CCExec(), lv.tcorr, 0.0);
4606 teleTransition(L, sym, lv.res, lv.tcorr); // §5.6 (a rank idling below holds no L + 1)
4607 fp32AddDouble(lv.xf, CCConst(lv.tcorr), lv.ext, lv.g);
4608 } else if (L == fp32Last_) { // the bottom interface (L + 2 == lv_.size()): FP64 below
4609 Level& cs = lv_[L + 1];
4610 restrictFp32ToDZeroX(cs.rhs, cs.x, VConst(lv.resf), cs.ext, lv.ext, cs.g, lv.g, cs.inner,
4611 lv.ratio);
4612 Kokkos::deep_copy(CCExec(), cs.x, 0.0);
4613 vcycle(L + 1, sym);
4614 if (symVcycle_) { // A3.3 item 2: the constant form, no coarse-ghost refresh
4615 prolongConstFp32FromD(lv.xf, CCConst(cs.x), lv.ext, cs.ext, lv.g, cs.g, lv.inner, lv.ratio);
4616 } else {
4617 fill(cs, cs.x);
4618 applyOutflowGhost(cs, cs.x, cs.g);
4619 applyNeumannGhost(cs, cs.x, cs.g);
4620 prolongFp32FromD(lv.xf, CCConst(cs.x), lv.ext, cs.ext, lv.g, cs.g, lv.inner, lv.ratio);
4621 }
4622 } else {
4623 Level& cs = lv_[L + 1];
4624 restrictFp32ZeroX(cs.rhsf, cs.xf, VConst(lv.resf), cs.ext, lv.ext, cs.g, lv.g, cs.inner,
4625 lv.ratio);
4626 Kokkos::deep_copy(CCExec(), cs.xf, 0.0f);
4627 vcycleFp32Dist(L + 1, sym);
4628 if (symVcycle_) {
4629 prolongConstFp32(lv.xf, VConst(cs.xf), lv.ext, cs.ext, lv.g, cs.g, lv.inner, lv.ratio);
4630 } else {
4631 fill(cs, cs.xf); // the level's FP32 ghost exchange (devf)
4632 applyNeumannGhost(cs, cs.xf, cs.g);
4633 prolongFp32(lv.xf, VConst(cs.xf), lv.ext, cs.ext, lv.g, cs.g, lv.inner, lv.ratio);
4634 }
4635 }
4636 smoothFp32Dist(lv, post_, /*reverse=*/sym, false);
4637 }
4638 // smooth()'s distributed branches on the FP32 data: the communication-avoiding pair on a g = 2
4639 // level (never level 0, so never skipFirst), else the per-colour exchange overlapped with the
4640 // interior sweep. skipFirst: the level-0 entry already did the first colour.
4641 void smoothFp32Dist(Level& lv, int sweeps, bool reverse, bool skipFirst) {
4642 if (lineRelaxOn(lv)) { // A2.4: column colours, the per-colour exchange (no CA pair)
4643 for (int k = 0; k < sweeps; ++k)
4644 for (int s = 0; s < 2; ++s) {
4645 if (skipFirst) {
4646 skipFirst = false;
4647 continue;
4648 }
4649 lineSmoothColorFp32(lv, lv.lineAxis, reverse ? (1 - s) : s);
4650 }
4651 return;
4652 }
4653 const C3 og = parityOg(lv);
4654 const int g = lv.g;
4655 const C3 e = lv.ext;
4656 const C3 lo{g + 1, g + 1, g + 1};
4657 const C3 hi{e.x - g - 1, e.y - g - 1, e.z - g - 1};
4658 const C3 none{0, 0, 0};
4659 auto box = [&](int color, C3 a, C3 b, C3 exLo, C3 exHi) {
4660 cutcellSmoothColorFp32Box(lv.xf, VConst(lv.rhsf), VConst(lv.WX), VConst(lv.WY), VConst(lv.WZ),
4661 e, og, color, a, b, exLo, exHi);
4662 };
4663 if (caSmooth(lv)) {
4664 const C3 rlo{g - 1, g - 1, g - 1};
4665 const C3 rhi{e.x - g + 1, e.y - g + 1, e.z - g + 1};
4666 lv.devf->exchange(lv.rhsf); // ring rhs (owner's inner values), fixed over the sweeps
4667 for (int k = 0; k < sweeps; ++k) {
4668 const int c0 = reverse ? 1 : 0, c1 = 1 - c0;
4669 lv.devf->exchangeBegin(lv.xf);
4670 box(c0, lo, hi, none, none);
4671 lv.devf->exchangeEnd(lv.xf);
4672 box(c0, rlo, rhi, lo, hi);
4673 box(c1, C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g}, none, none);
4674 }
4675 return;
4676 }
4677 // K3 (§5.2): the stencil halo and the in-kernel wrap, as smooth()'s distributed branch.
4678 const int m = stencilWrap(lv);
4679 const C3 wlo = boxLo(g, m), whi = boxHi(e, g, m);
4680 auto wbox = [&](int color, C3 a, C3 b, C3 exLo, C3 exHi) {
4681 cutcellSmoothColorFp32Box(lv.xf, VConst(lv.rhsf), VConst(lv.WX), VConst(lv.WY), VConst(lv.WZ),
4682 e, og, color, a, b, exLo, exHi, m, g);
4683 };
4684 for (int k = 0; k < sweeps; ++k)
4685 for (int s = 0; s < 2; ++s) {
4686 if (skipFirst) {
4687 skipFirst = false;
4688 continue;
4689 }
4690 const int color = reverse ? (1 - s) : s;
4691 if (m == 7) {
4692 wbox(color, wlo, whi, none, none);
4693 continue;
4694 }
4695 GridHalo<VReal>& h = stencilHaloF(lv);
4696 h.exchangeBegin(lv.xf);
4697 wbox(color, wlo, whi, none, none);
4698 h.exchangeEnd(lv.xf);
4699 wbox(color, C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g}, wlo, whi);
4700 }
4701 }
4702 // vcycleImpl's distributed residual on the FP32 data: the exchange overlapped with the interior.
4703 void residualFp32Dist(Level& lv) {
4704 const int g = lv.g;
4705 const C3 e = lv.ext;
4706 const int m = stencilWrap(lv); // K3 (§5.2), as in residual's distributed branch
4707 const C3 lo = boxLo(g, m), hi = boxHi(e, g, m);
4708 if (m == 7) {
4709 residualFp32Box(lv.resf, VConst(lv.xf), VConst(lv.rhsf), VConst(lv.WX), VConst(lv.WY),
4710 VConst(lv.WZ), e, lo, hi, C3{0, 0, 0}, C3{0, 0, 0}, m, g);
4711 return;
4712 }
4713 GridHalo<VReal>& h = stencilHaloF(lv);
4714 h.exchangeBegin(lv.xf);
4715 residualFp32Box(lv.resf, VConst(lv.xf), VConst(lv.rhsf), VConst(lv.WX), VConst(lv.WY),
4716 VConst(lv.WZ), e, lo, hi, C3{0, 0, 0}, C3{0, 0, 0}, m, g);
4717 h.exchangeEnd(lv.xf);
4718 residualFp32Box(lv.resf, VConst(lv.xf), VConst(lv.rhsf), VConst(lv.WX), VConst(lv.WY),
4719 VConst(lv.WZ), e, C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g}, lo, hi, m, g);
4720 }
4721#endif
4722 // §4.4.4 item 4, the level-0 EXIT (replaces removeMean(l0, z) and the r^T z dot): the fluid
4723 // mean m of (double)xf (C0's lane order on a host backend), then one pass z = s ((double)xf - m)
4724 // on fluid cells and z = s (double)xf on the other inner cells (s = 2^e), accumulating r^T z over
4725 // the fluid cells into slot k (C4's order) when k >= 0, and p = z when p is allocated.
4726 void exitFp32(Level& l0, CCField zz, CCField rr, double s, int k, CCField p) {
4727 const C3 e = l0.ext;
4728 const int g = l0.g;
4729 VConst xf = l0.xf;
4730 CCField z = zz, pp = p;
4731 CCConst r = rr;
4732 FPV ac = l0.AC;
4733 const bool counted = kHostMemory && l0.nFluid >= 0; // H-1: the precomputed fluid count
4734 const bool all = counted && l0.allFluid;
4735 const long cnt0 = l0.nFluid;
4736 // S1 (doc/vof_gpu_coarse_tail_design.md §5.1): on a device, single rank, the count counted at
4737 // the operator build (no count reduction here, so the mean is a single-result reduction)
4738 const bool devCounted = !kHostMemory && !distributed_ && l0.nFluidDevValid;
4739 auto ks = ks_;
4740 auto kc = devCounted ? l0.nFluidDev : kcnt_;
4741 // the joint {sum, count} body (no precomputed count)
4742 auto joint = KOKKOS_LAMBDA(int x, int y, int zc, double& a, long& c) {
4743 const long i = (long)x + (long)y * e.x + (long)zc * (long)e.x * e.y;
4744 if (ac(i) > 1e-30f) {
4745 a += (double)xf(i);
4746 c += 1;
4747 }
4748 };
4749 if (!distributed_) {
4750 if (devCounted)
4752 "peclet::flow::mgmeanr_f32", C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g},
4753 KOKKOS_LAMBDA(int x, int y, int zc, double& a) {
4754 const long i = (long)x + (long)y * e.x + (long)zc * (long)e.x * e.y;
4755 if (ac(i) > 1e-30f)
4756 a += (double)xf(i);
4757 },
4758 Kokkos::Sum<double, CCMem>(slot(kMsum)));
4759 else if (counted)
4761 "peclet::flow::mgmeanr_f32", C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g},
4762 KOKKOS_LAMBDA(int x, int y, int zc, double& a) {
4763 const long i = (long)x + (long)y * e.x + (long)zc * (long)e.x * e.y;
4764 if (all || ac(i) > 1e-30f)
4765 a += (double)xf(i);
4766 },
4767 Kokkos::Sum<double, CCMem>(slot(kMsum)));
4768 else
4769 ccReduce3Lanes("peclet::flow::mgmeanr_f32", C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g},
4770 joint, Kokkos::Sum<double, CCMem>(slot(kMsum)),
4771 Kokkos::Sum<long, CCMem>(kcnt_));
4772 } else {
4773#ifdef PECLET_FLOW_MPI
4774 // D-dist §5.5 (nFluid = -1 here, so the joint body): the {sum, count} pair reduced straight
4775 // into host scalars -- ONE device->host sync, as the FP64 distributed removeMean (the same
4776 // reduction as into the device slots, only the result's location differs)
4777 double sum = 0.0;
4778 long lcnt = 0;
4779 ccReduce3Lanes("peclet::flow::mgmeanr_f32", C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g}, joint,
4780 sum, lcnt);
4781 double dcnt = (double)lcnt;
4782 allreduceSum2(sum, dcnt, l0.comm); // the one Allreduce removeMean spends
4783 const long gcnt = (long)dcnt;
4784 Kokkos::parallel_for( // the global values back into the same slots (async, no fence)
4785 "peclet::flow::mgmeanr_f32_global", Kokkos::RangePolicy<CCExec>(CCExec(), 0, 1),
4786 KOKKOS_LAMBDA(int) {
4787 ks(kMsum) = sum;
4788 kc() = gcnt;
4789 });
4790#endif
4791 }
4792 const bool copyP = p.extent(0) != 0;
4793 auto body = KOKKOS_LAMBDA(int x, int y, int zc, double& acc) {
4794 const long i = (long)x + (long)y * e.x + (long)zc * (long)e.x * e.y;
4795 const long cnt = counted ? cnt0 : kc();
4796 const bool fluid = all || ac(i) > 1e-30f;
4797 const double xd = (double)xf(i);
4798 const double zi = (fluid && cnt != 0) ? s * (xd - ks(kMsum) / (double)cnt) : s * xd;
4799 z(i) = zi;
4800 if (copyP)
4801 pp(i) = zi;
4802 if (fluid)
4803 acc += r(i) * zi;
4804 };
4805 if (k >= 0) {
4806 ccReduce3Lanes("peclet::flow::mgmeans_dot_f32", C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g},
4807 body, slot(k));
4808 } else {
4809 ccFor3(
4810 "peclet::flow::mgmeans_f32", C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g},
4811 KOKKOS_LAMBDA(int x, int y, int zc) {
4812 double unused = 0.0;
4813 body(x, y, zc, unused);
4814 });
4815 }
4816 }
4817 // Test hook (tests/kokkos/test_mg_fp32_vcycle.cpp): mark / unmark an overlay solve, as
4818 // OverlayScope does for the star and ghost-projection drivers.
4819 void debugSetOverlaySolve(bool on) { overlaySolve_ = on; }
4820 // K3 test hook (mg_stencil_halo_np*): force the full `dev` halo and wrapMask = 0 on every
4821 // stencil exchange (today's code), to compare against the default bitwise.
4822 void debugSetStencilHaloOff(bool on) { stencilHaloOff_ = on; }
4823 void setVcyclePrecision(int mode) {
4824 if (mode != kVcycleAuto && mode != kVcycleFp64 && mode != kVcycleFp32)
4825 throw std::invalid_argument(
4826 "CutcellMG::setVcyclePrecision: kVcycleAuto | kVcycleFp64 | kVcycleFp32");
4827 fp32Latched_ = false; // R (§4): any call re-arms 'auto'
4828 const bool was = fp64Deferrable();
4829 vprec_ = mode;
4830 if (!was && fp64Deferrable())
4831 releaseFp64(); // D5 (§4.4.7)
4832 buildFp32Weights(); // takes effect at once (§4.4.6)
4833 }
4834 int vcyclePrecision() const { return vprec_; }
4835 // The precision the last solve's V-cycles used (§4.4.6): true = FP32.
4836 bool lastVcycleFp32() const { return lastVcycleFp32_; }
4837 // R (doc/vof_projection_distributed_design.md §4), C++ only: the number of FP64 restarts, the
4838 // discarded iterations of the last restarted FP32 attempt, whether the last attempt converged.
4839 int vcycleRestarts() const { return vcycleRestarts_; }
4840 int lastDiscardedIters() const { return lastDiscardedIters_; }
4841 bool lastSolveConverged() const { return lastSolveConverged_; }
4842 // R test hook (C++ only, no Python, no env): kind 1 = on the at-th FP32 V-cycle of an attempt
4843 // the exit scale is NaN (z and r^T z non-finite on every rank); kind 2 = an FP32 attempt runs
4844 // with maxit = min(maxit, at); kind 0 = off. Inert unless the V-cycle is FP32.
4845 void debugSetFp32Fault(int kind, int at) {
4846 fp32FaultKind_ = kind;
4847 fp32FaultAt_ = at;
4848 }
4849 // R (§4): a failed attempt of this solve will be restarted, so a breakdown does not throw under
4850 // set_pressure_strict (the FP64 restart attempt honours strict as any FP64 solve).
4851 bool restartArmed() const { return vprec_ == kVcycleAuto && lastVcycleFp32_; }
4852 // The decoupled cells of a carrying level, counted two ways: FP32 (all six weights 0, D_i == 0)
4853 // and FP64 (AC < 1e-30). The face-range check makes the sets equal (§4.4.1 (5)).
4854 void fp32DecoupledCounts(int L, long& n32, long& n64) {
4855 ensureFp64(); // D5: reads AC (test hook)
4856 const Level& lv = lv_[L];
4857 const C3 e = lv.ext;
4858 const int g = lv.g;
4859 Kokkos::View<const VReal*, CCMem> WX = lv.WX, WY = lv.WY, WZ = lv.WZ;
4860 FPV AC = lv.AC;
4861 n32 = 0;
4862 n64 = 0;
4863 ccReduce3(
4864 "peclet::flow::mg_fp32_decoupled", C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g},
4865 KOKKOS_LAMBDA(int lx, int ly, int lz, long& a, long& b) {
4866 const long sx = 1, sy = e.x, sz = (long)e.x * e.y;
4867 const long i = (long)lx + (long)ly * sy + (long)lz * sz;
4868 if (WX(i) == 0.0f && WX(i + sx) == 0.0f && WY(i) == 0.0f && WY(i + sy) == 0.0f &&
4869 WZ(i) == 0.0f && WZ(i + sz) == 0.0f)
4870 a += 1;
4871 if (AC(i) < 1e-30)
4872 b += 1;
4873 },
4874 n32, n64);
4875 }
4876#ifndef NDEBUG
4878 if (fp64Stale_)
4879 return; // D5: the FP64 AC of a deferred level is not built (the test hook ensures it)
4880 for (int L = 0; L < (int)lv_.size(); ++L)
4881 if (fp32WeightsOk(L)) {
4882 long n32 = 0, n64 = 0;
4883 fp32DecoupledCounts(L, n32, n64);
4884 assert(n32 == n64 && "D: the FP32 decoupled set must equal the FP64 AC < 1e-30 set");
4885 }
4886 }
4887#endif
4888 // Eligibility of the FP32 V-cycle for the current solve (§4.4.1): nullptr when every condition
4889 // holds, else the first failed one. `krylov`: the preconditioner is called from
4890 // solvePCGResident or solveFCG (condition 1).
4891 const char* fp32VcycleIneligible(bool krylov) const {
4892 if (!krylov)
4893 return "the V-cycle is not the preconditioner of the single-rank PCG or FCG driver";
4894#ifdef PECLET_FLOW_MPI
4895 if (distributed_)
4896 return fp32VcycleIneligibleDist();
4897#endif
4898 if (hasOutflow_)
4899 return "an outflow face is present";
4900 if (overlaySolve_)
4901 return "the solve carries an overlay (star couplings / ghost projection)";
4902 if (lv_.size() < 2)
4903 return "the hierarchy has a single level";
4904 for (std::size_t L = 0; L + 1 < lv_.size(); ++L)
4905 if (!fusedWrapSmooth(lv_[L]))
4906 return "a non-bottom level has an odd inner dimension";
4907 if (!(exactResidual_ || std::is_same_v<MReal, double>))
4908 return "the outer operator is float (MReal = float without the exact residual)";
4909 // §4.2 P8: the scheme removes the mean at the level-0 exit only ("fine scope, as today"); the
4910 // legacy every-level scope (set_pressure_mean_removal('all')) keeps the FP64 V-cycle.
4911 if (meanRemovalAll_)
4912 return "the mean-removal scope is 'all' (the FP32 V-cycle removes the mean at level 0 only)";
4913 for (int L = 0; L + 1 < (int)lv_.size(); ++L)
4914 if (!fp32WeightsOk(L))
4915 return "a face weight is outside {0} or [1e-30, 1e30] (or the FP32 weights are not built)";
4916 return nullptr;
4917 }
4918#ifdef PECLET_FLOW_MPI
4919 // D-dist (doc/vof_projection_distributed_design.md §5.2): the distributed conditions, every one
4920 // from global data (flags allreduced, global inner dimensions), so every rank takes the same
4921 // branch. At np = 1 each equals its single-rank counterpart (global = local dimensions, no
4922 // telescope), so 'auto' picks the single-rank precision. Collective (fp32WeightsOk).
4923 const char* fp32VcycleIneligibleDist() const {
4924 if (hasOutflow_)
4925 return "an outflow face is present";
4926 if (overlaySolve_)
4927 return "the solve carries an overlay (star couplings / ghost projection)";
4928 if (fp32Last_ < 0)
4929 return "the hierarchy has a single level";
4930 for (int L = 0; L <= fp32Last_; ++L) {
4931 const C3 gi = lv_[L].gdim; // the level's global inner dimensions (globalInner)
4932 if (gi.x % 2 != 0 || gi.y % 2 != 0 || gi.z % 2 != 0)
4933 return "a level the FP32 V-cycle runs on has an odd global inner dimension";
4934 }
4935 if (!(exactResidual_ || std::is_same_v<MReal, double>))
4936 return "the outer operator is float (MReal = float without the exact residual)";
4937 if (meanRemovalAll_)
4938 return "the mean-removal scope is 'all' (the FP32 V-cycle removes the mean at level 0 only)";
4939 bool ok = true;
4940 for (int L = 0; L <= fp32Last_; ++L)
4941 ok = fp32WeightsOk(L) && ok; // every level evaluated: the first call is collective
4942 if (!ok)
4943 return "a face weight is outside {0} or [1e-30, 1e30] (or the FP32 weights are not built)";
4944 return nullptr;
4945 }
4946#endif
4947 // ---- A2.4: the zebra line smoother (doc/mg_depth_policy.md Amendment A2.4, WO-7) -------------
4948 // On a triggered smoothed level (lineAxis = s >= 0) with LR on and s whole on every rank (the
4949 // level decomposition has one block along s), every point-smoothing call sweeps two COLUMN
4950 // colours instead of two cell colours; a split s keeps point RB-GS there. Read at smoothing time.
4951 bool lineRelaxOn(const Level& lv) const {
4952 return lineRelax_ && lv.lineAxis >= 0 && ((lv.wholeAxes >> lv.lineAxis) & 1);
4953 }
4954 // s periodic: both domain faces on s periodic (the cyclic column system, Sherman-Morrison).
4955 bool linePeriodic(int s) const { return bc_[2 * s] == 0 && bc_[2 * s + 1] == 0; }
4956 // One FP64 column colour on level lv along s. Before it, what the level's point path does before
4957 // a colour in its non-CA form: single rank the fill + applyOutflowGhost, or the fused-wrap reads;
4958 // distributed the stencil-halo exchange + applyOutflowGhost (no exchange when every axis wraps).
4959 void lineSmoothColor(Level& lv, int s, int color) {
4960 int m = 0;
4961#ifdef PECLET_FLOW_MPI
4962 if (distributed_) {
4963 m = stencilWrap(lv);
4964 if (m != 7) {
4965 stencilHalo(lv).exchange(lv.x);
4966 applyOutflowGhost(lv, lv.x, lv.g);
4967 }
4968 } else
4969#endif
4970 {
4971 if (fusedWrapSmooth(lv)) {
4972 m = 7;
4973 } else {
4974 fill(lv, lv.x);
4975 applyOutflowGhost(lv, lv.x, lv.g);
4976 }
4977 }
4978 lineRelaxColorFace(lv.x, CCConst(lv.rhs), FPC(lv.AC), FPC(lv.AFX), FPC(lv.AFY), FPC(lv.AFZ),
4979 lv.lnc, lv.lny, lv.lnz, lv.ext, parityOg(lv), lv.g, s, linePeriodic(s), m,
4980 color);
4981 }
4982 // One FP32 column colour: single rank the in-kernel wrap (smoothFp32's reads); distributed the
4983 // FP32 stencil-halo exchange (no outflow face on the FP32 path: eligibility).
4984 void lineSmoothColorFp32(Level& lv, int s, int color) {
4985 int m = 7;
4986#ifdef PECLET_FLOW_MPI
4987 if (distributed_) {
4988 m = stencilWrap(lv);
4989 if (m != 7)
4990 stencilHaloF(lv).exchange(lv.xf);
4991 }
4992#endif
4993 lineRelaxColorFp32(lv.xf, VConst(lv.rhsf), VConst(lv.WX), VConst(lv.WY), VConst(lv.WZ), lv.lncf,
4994 lv.lnyf, lv.lnzf, lv.ext, parityOg(lv), lv.g, s, linePeriodic(s), m, color);
4995 }
4996 // Marks a solve that carries an overlay (star couplings / the ghost-projection BiCGStab) for its
4997 // whole duration, every exit path included.
4999 bool& flag;
5000 OverlayScope(bool& f, bool on) : flag(f) { flag = on; }
5001 ~OverlayScope() { flag = false; }
5002 };
5003 void smooth(Level& lv, int sweeps, bool reverse) {
5004 if (lineRelaxOn(lv)) { // A2.4: column colours on a triggered level (no CA pair)
5005 for (int k = 0; k < sweeps; ++k)
5006 for (int s = 0; s < 2; ++s)
5007 lineSmoothColor(lv, lv.lineAxis, reverse ? (1 - s) : s);
5008 return;
5009 }
5010 const C3 og = parityOg(lv); // red-black parity origin ({0,0,0} single-rank)
5011#ifdef PECLET_FLOW_MPI
5012 if (caSmooth(lv)) {
5013 // Communication-avoiding pair: ONE 2-deep exchange per red-black pair instead of a 1-deep
5014 // exchange per colour. The first colour overlaps its exchange with the interior sweep, then
5015 // sweeps the boundary shell PLUS the 1-deep ghost ring — redundantly recomputing the
5016 // neighbour's boundary cells from the same operands the neighbour uses (2-deep x ghosts,
5017 // ring rows of the operator and rhs are exchanged/assembled bit-identical), so the ring
5018 // values come out equal to what a fresh exchange would deliver. The second colour then
5019 // sweeps with NO exchange: its boundary cells read only first-colour ring cells (a colour
5020 // never reads its own colour). Bit-identical to the per-colour exchange at half the events.
5021 const int g = lv.g;
5022 const C3 lo{g + 1, g + 1, g + 1};
5023 const C3 hi{lv.ext.x - g - 1, lv.ext.y - g - 1, lv.ext.z - g - 1};
5024 const C3 rlo{g - 1, g - 1, g - 1};
5025 const C3 rhi{lv.ext.x - g + 1, lv.ext.y - g + 1, lv.ext.z - g + 1};
5026 lv.dev->exchange(lv.rhs); // ring rhs (owner's inner values); rhs is fixed over the sweeps
5027 for (int k = 0; k < sweeps; ++k) {
5028 const int c0 = reverse ? 1 : 0, c1 = 1 - c0;
5029 lv.dev->exchangeBegin(lv.x);
5030 cutcellSmoothColorBoxFace(lv.x, CCConst(lv.rhs), FPC(lv.AC), FPC(lv.AFX), FPC(lv.AFY),
5031 FPC(lv.AFZ), lv.ext, og, c0, lo, hi, C3{0, 0, 0}, C3{0, 0, 0});
5032 lv.dev->exchangeEnd(lv.x);
5033 cutcellSmoothColorBoxFace(lv.x, CCConst(lv.rhs), FPC(lv.AC), FPC(lv.AFX), FPC(lv.AFY),
5034 FPC(lv.AFZ), lv.ext, og, c0, rlo, rhi, lo, hi);
5035 cutcellSmoothColorFace(lv.x, CCConst(lv.rhs), FPC(lv.AC), FPC(lv.AFX), FPC(lv.AFY),
5036 FPC(lv.AFZ), lv.ext, og, g, c1);
5037 }
5038 return;
5039 }
5040#endif
5041 for (int k = 0; k < sweeps; ++k)
5042 for (int s = 0; s < 2; ++s) {
5043 const int color = reverse ? (1 - s) : s;
5044#ifdef PECLET_FLOW_MPI
5045 if (distributed_) {
5046 // Overlap the per-color halo with the interior sweep: post the exchange, smooth the
5047 // cells whose 7-point stencil reads no ghost (they depend on neither the incoming halo
5048 // nor the outflow ghost), complete the exchange, then sweep the boundary shell. A
5049 // color's cells never read same-color cells, so this ordering is bit-identical to the
5050 // blocking fill-then-full-sweep (validated by the np>1 bit-exact MG tests).
5051 // K3 (§5.2): the stencil halo; on the wrap axes the box spans the block whole and
5052 // reads the wrap in-kernel; every axis wrapped (np 1): no exchange, one launch.
5053 const int g = lv.g;
5054 const int m = stencilWrap(lv);
5055 const C3 lo = boxLo(g, m), hi = boxHi(lv.ext, g, m);
5056 if (m == 7) {
5057 cutcellSmoothColorBoxFace(lv.x, CCConst(lv.rhs), FPC(lv.AC), FPC(lv.AFX), FPC(lv.AFY),
5058 FPC(lv.AFZ), lv.ext, og, color, lo, hi, C3{0, 0, 0},
5059 C3{0, 0, 0}, m, g);
5060 continue;
5061 }
5062 GridHalo<double>& h = stencilHalo(lv);
5063 h.exchangeBegin(lv.x);
5064 cutcellSmoothColorBoxFace(lv.x, CCConst(lv.rhs), FPC(lv.AC), FPC(lv.AFX), FPC(lv.AFY),
5065 FPC(lv.AFZ), lv.ext, og, color, lo, hi, C3{0, 0, 0},
5066 C3{0, 0, 0}, m, g);
5067 h.exchangeEnd(lv.x);
5068 applyOutflowGhost(lv, lv.x, g);
5069 cutcellSmoothColorBoxFace(lv.x, CCConst(lv.rhs), FPC(lv.AC), FPC(lv.AFX), FPC(lv.AFY),
5070 FPC(lv.AFZ), lv.ext, og, color, C3{g, g, g},
5071 C3{lv.ext.x - g, lv.ext.y - g, lv.ext.z - g}, lo, hi, m, g);
5072 continue;
5073 }
5074#endif
5075 if (fusedWrapSmooth(lv)) { // A3: no fill; the pass reads the periodic wrap directly
5076 cutcellSmoothColorFaceWrap(lv.x, CCConst(lv.rhs), FPC(lv.AC), FPC(lv.AFX), FPC(lv.AFY),
5077 FPC(lv.AFZ), lv.ext, lv.inner, og, lv.g, color);
5078 continue;
5079 }
5080 fill(lv, lv.x);
5081 applyOutflowGhost(lv, lv.x, lv.g);
5082 cutcellSmoothColorFace(lv.x, CCConst(lv.rhs), FPC(lv.AC), FPC(lv.AFX), FPC(lv.AFY),
5083 FPC(lv.AFZ), lv.ext, og, lv.g, color);
5084 }
5085 }
5086
5087 // --- when to agglomerate
5088 // ------------------------------------------------------------------------ A V-cycle only
5089 // converges at a rate independent of the domain if its COARSEST level is small enough to be
5090 // solved (essentially) exactly by the few smoother sweeps applied there. A geometric hierarchy
5091 // cannot always get there: an axis stops coarsening once it turns odd, and under MPI it stops
5092 // once any rank's block turns odd — so on a fixed per-rank block the coarsest GLOBAL grid grows
5093 // with the rank count and the bottom is progressively under-solved. That is the mechanism behind
5094 // weak-scaling curves that decay while communication stays negligible.
5095 //
5096 // Measured (single GPU, channel, Lx = 2048 x 64 x 64, everything else held): a smoothed bottom
5097 // needs 13.5 pressure iterations/step at 4 levels and 6.0 at 6 levels, against 4.4 at full
5098 // geometric depth. Agglomerating and solving that same bottom exactly gives 4.0 at BOTH 4 and 6
5099 // levels — depth-independent, and faster in wall-clock than the full-depth hierarchy (69.5 vs
5100 // 77.1 ms/step) because the extra levels cost more than the coarse solve they replace.
5101 //
5102 // NOT the default yet, and the reason is measured: on the cut-cell sphere-packing regression
5103 // (random_spheres, N=48) switching the bottom to the agglomerated solve makes the OUTER iteration
5104 // count WORSE (442 -> 622 total, +41 %) at unchanged accuracy, so the assembled coarse operator
5105 // is evidently not consistent with the V-cycle's on that IBM path. Until that is understood,
5106 // `auto` is opt-in and the legacy smoothed bottom stays the default. `mode`: 0 = never / plain
5107 // smoothed bottom (DEFAULT), -1 = auto, 1 = always. `setAgglomerationExtent` moves the
5108 // threshold; the ideal bottom is a handful of cells per axis.
5109 bool agglomerateBottom() const {
5110 if (agglomMode_ == 0)
5111 return false;
5112 if (agglomMode_ == 1)
5113 return true;
5114 if (lv_.empty())
5115 return false;
5116 // coarsest GLOBAL cell count (the local block does not decide how hard the coarse solve is)
5117 long gx = gnxF_, gy = gnyF_, gz = gnzF_;
5118 for (int L = 0; L + 1 < (int)lv_.size(); ++L) {
5119 gx /= lv_[L].ratio.x;
5120 gy /= lv_[L].ratio.y;
5121 gz /= lv_[L].ratio.z;
5122 }
5123 return agglomerateAuto(gx, gy, gz);
5124 }
5125 // agglomerateBottom's 'auto' (-1) answer for a coarsest GLOBAL grid gx x gy x gz.
5126 bool agglomerateAuto(long gx, long gy, long gz) const {
5127 // Auto engages only for the SINGULAR (periodic / all-Neumann / IBM) operator. On the
5128 // Dirichlet-anchored (outflow) path the exact bottom measurably LOWERS the outer solve's
5129 // attainable floor (128x32x32 inflow/outflow channel: flux divergence floor 8e-8 smoothed vs
5130 // 2e-5 agglomerated at identical budgets; the CSR solution satisfies the V-cycle's own bottom
5131 // operator to 1e-9, so this is not operator mismatch — the anchored operator's near-null mode
5132 // makes the exact bottom return O(1e3 |b|) corrections whose float-hierarchy round-off the
5133 // smoothed bottom never generates). Until that is understood, anchored operators keep the
5134 // smoothed bottom; set_pressure_bottom("agglomerated") still forces it anywhere.
5135 if (!removeMean_)
5136 return false;
5137 // The criterion is the coarsest grid's largest EXTENT, not its cell count: what a few smoother
5138 // sweeps cannot fix is a mode spanning many cells along an axis, and Gauss-Seidel needs O(L^2)
5139 // sweeps to damp a wavelength of L cells. A 64x2x2 bottom is only 256 cells yet still 64 across
5140 // -- measured, that costs 6.0 pressure iterations/step against 4.0 for an exact solve.
5141 const int thresh = agglomExtent_ > 0 ? agglomExtent_ : 4;
5142 return gx > thresh || gy > thresh || gz > thresh;
5143 }
5144
5145 // doc/mg_depth_policy.md §4.1: may a level of GLOBAL inner dims g be the AUTO depth's bottom?
5146 // Every axis <= the bottom extent (a smoothed bottom suffices), or -- for the singular operator
5147 // with agglomeration not forced off -- the direct engine's own admission (n <= kBottomMaxCells
5148 // and an axis with planes of <= kBottomMaxPlane cells): one source of truth, a cap moves both.
5149 // Not here: the 1..64 fluid components (runtime; a bottom failing it takes GraphAMG, as today).
5150 // Pure and static, so predict() runs the same code; host, once per level per hierarchy build.
5151 static bool bottomAdmissible(C3 g, int extent, bool anchored, int agglomMode, const int bc[6]) {
5152 const int e = extent > 0 ? extent : 4; // set_pressure_bottom_extent
5153 if (g.x <= e && g.y <= e && g.z <= e)
5154 return true;
5155 if (anchored)
5156 return !kAnchoredFollowsGrid;
5157 if (agglomMode == 0) // 'smoother' forced: only a small bottom
5158 return false;
5159 const long n = (long)g.x * g.y * g.z;
5160 return n <= kBottomMaxCells && bottomChoosePlanes(g, bc).valid();
5161 }
5162 // bottomAdmissible on this hierarchy's live settings (all set before init / initMpi).
5163 bool bottomAdmissibleHere(C3 g) const {
5164 return bottomAdmissible(g, agglomExtent_, !removeMean_ || hasOutflow_, agglomMode_, bc_);
5165 }
5166 static std::string depthRequestLabel(int nLevels) {
5167 return nLevels == 0 ? std::string("auto") : std::to_string(nLevels);
5168 }
5169 // Debug output only (mgDebugLevel, §4.2 census): the depth AUTO resolves to on the hierarchy just
5170 // built, read off its levels' global dims (no second hierarchy). `more`: the last built level
5171 // could still coarsen, so an AUTO depth beyond it reads ">D". Under AUTO also the legacy depth-4
5172 // count.
5173 void printDepthCensus(int nLevels, bool more) const {
5174 const int D = (int)lv_.size();
5175 int a = -1;
5176 for (int L = kAutoMinLevels - 1; L < D && a < 0; ++L)
5177 if (bottomAdmissibleHere(lv_[L].gdim))
5178 a = L + 1;
5179 if (a < 0 && !more)
5180 a = D;
5181 const C3 b = lv_.back().gdim;
5182 // A2.3: the triggered smoothed levels, appended only where there are any (the line is
5183 // unchanged on every other hierarchy).
5184 std::string line;
5185 const std::vector<int> ls = lineSmoothedLevels();
5186 if (!ls.empty()) {
5187 line = "; A2 line-trigger smoothed levels {";
5188 for (std::size_t i = 0; i < ls.size(); ++i)
5189 line += (i ? "," : "") + std::to_string(ls[i]);
5190 line += std::string("} along ") + "xyz"[lv_[ls[0]].lineAxis];
5191 }
5192 // A3.3 item 4: the transfer pair and the smoothed bottom's sweep order.
5193 line += symVcycle_ ? "; P const, bottom palindromic" : "; P trilinear, bottom forward";
5194 if (a > 0)
5195 printf("[mg-census] depth requested %s -> %d levels, bottom %dx%dx%d; auto -> %d%s%s\n",
5196 depthRequestLabel(nLevels).c_str(), D, b.x, b.y, b.z, a,
5197 nLevels == 0 ? (" (legacy 4 -> " + std::to_string(std::min(D, 4)) + ")").c_str() : "",
5198 line.c_str());
5199 else
5200 printf("[mg-census] depth requested %s -> %d levels, bottom %dx%dx%d; auto -> >%d%s\n",
5201 depthRequestLabel(nLevels).c_str(), D, b.x, b.y, b.z, D, line.c_str());
5202 }
5203 // A2.3 accessors (lineRelaxOn reads lineAxis: the A2.4 line smoother). lineAxes():
5204 // every level's lineAxis (T holds: the strong axis s; else -1). lineSmoothedLevels(): the
5205 // TRIGGERED SMOOTHED levels -- T holds and the V-cycle smooths the level: every level above the
5206 // bottom, and the bottom when it is the smoothed bottom (not agglomerated into an exact solve).
5207 std::vector<int> lineAxes() const {
5208 std::vector<int> r;
5209 r.reserve(lv_.size());
5210 for (const Level& l : lv_)
5211 r.push_back(l.lineAxis);
5212 return r;
5213 }
5214 std::vector<int> lineSmoothedLevels() const {
5215 std::vector<int> r;
5216 const int D = (int)lv_.size();
5217 for (int L = 0; L < D; ++L)
5218 if (lv_[L].lineAxis >= 0 && (L + 1 < D || !agglomerateBottom()))
5219 r.push_back(L);
5220 return r;
5221 }
5222 // The table suffix of level L: " A' <A'>" where a unique strong axis exists, plus " T <axis>"
5223 // when the trigger holds; empty otherwise (the table is unchanged on every isotropic level).
5224 std::string lineAxisLabel(int L) const {
5225 const Level& l = lv_[L];
5226 if (!(l.strongAspect > 0.0))
5227 return std::string();
5228 char buf[64];
5229 if (l.lineAxis >= 0)
5230 std::snprintf(buf, sizeof buf, " A' %g T %c", l.strongAspect, "xyz"[l.lineAxis]);
5231 else
5232 std::snprintf(buf, sizeof buf, " A' %g", l.strongAspect);
5233 return std::string(buf);
5234 }
5235
5236 // --- The direct bottom solve (doc/vof_step_performance_design.md §5.7, §5.14, §13, §14 H-1) ---
5237 static constexpr bool kHostMemory =
5238 std::is_same_v<typename CCExec::memory_space, Kokkos::HostSpace>;
5239 // Eligibility (§13.4.6: §5.7 conditions 1-6 -- 6 = B1b's 1-64 fluid components -- and an axis
5240 // whose planes hold at most kBottomMaxPlane cells): nullptr when the device bottom may run, else
5241 // the first failed condition. Host-cheap: the components are labelled once per hierarchy
5242 // (evalBottomComponents, at the first setOpenness after init) and cached -- the rho / eps / drag
5243 // rescaling of the per-step setOpenness never closes a face, so it cannot change the answer.
5244 const char* directBottomIneligible() const {
5245 if (distributed_ && !kHostMemory) // §14 H-6: the device keeps it (CUDA-aware MPI unresolved)
5246 return "the solve is distributed (multi-rank)";
5247 if (!removeMean_ || hasOutflow_)
5248 return "the operator is not the singular one (an outflow face is present)";
5249 if (!agglomerateBottom())
5250 return "the bottom is not agglomerated (set_pressure_bottom / set_pressure_bottom_extent)";
5251 if (lv_.empty() ||
5252 (long)lv_.back().gdim.x * lv_.back().gdim.y * lv_.back().gdim.z > kBottomMaxCells)
5253 return "the bottom level has more than 8192 inner cells"; // GLOBAL (== inner single rank)
5255 }
5256 // The conditions only a rank holding the bottom can evaluate (the labels and the planes, fixed
5257 // per hierarchy): 0 = met, 1 = no operator yet, 2 = components, 3 = planes.
5258 int bottomLabelCode() const {
5259 if (gbActive_ && !dirPlanes_.valid()) // gb_'s labels ran on no operator (buildGlobalBottomOp)
5260 return 3;
5261 if (!bottomConnKnown_)
5262 return 1;
5263 if (!bottomConnected_)
5264 return 2;
5265 if (!dirPlanes_.valid())
5266 return 3;
5267 return 0;
5268 }
5269 static const char* bottomLabelWhy(int code) {
5270 switch (code) {
5271 case 1:
5272 return "the pressure operator has not been built (no setOpenness since the hierarchy)";
5273 case 2:
5274 return "the bottom level has no fluid cell or more than 64 fluid components (B1b)";
5275 case 3:
5276 return "no axis gives planes of at most 192 cells (the direct factor's cap)";
5277 default:
5278 return nullptr;
5279 }
5280 }
5281 // Review note 1: an explicit 'direct' that is ineligible must raise on EVERY rank -- a rank
5282 // idling below a telescope point never reaches the bottom, and its own lv_ ends at the telescope
5283 // level, so directBottomIneligible() there reads the wrong level. This is
5284 // directBottomIneligible() on rank-uniform inputs: the live replicated settings plus the bottom's
5285 // global dims and label code agreed over comm_ once per hierarchy (agreeDirectBottom, at its
5286 // first operator build). On a rank holding the bottom the agreed values are its own, so it
5287 // answers as directBottomIneligible() does. Single rank: directBottomIneligible() itself.
5288 const char* directBottomIneligibleAll() const {
5289 if (!distributed_)
5290 return directBottomIneligible();
5291 if (!kHostMemory)
5292 return "the solve is distributed (multi-rank)";
5293 if (!removeMean_ || hasOutflow_)
5294 return "the operator is not the singular one (an outflow face is present)";
5295 if (!dirAgreedKnown_)
5296 return bottomLabelWhy(1);
5297 const C3 e = dirAgreedExt_, d = dirAgreedGdim_;
5298 if (!(agglomMode_ == 1 || (agglomMode_ != 0 && agglomerateAuto(e.x, e.y, e.z))))
5299 return "the bottom is not agglomerated (set_pressure_bottom / set_pressure_bottom_extent)";
5300 if ((long)d.x * d.y * d.z > kBottomMaxCells)
5301 return "the bottom level has more than 8192 inner cells";
5302 return bottomLabelWhy(dirAgreedCode_);
5303 }
5304 void requireDirectBottom() const {
5305 if (bottomSolver_ != kBottomDirect)
5306 return;
5307 if (const char* why = directBottomIneligibleAll())
5308 throw std::runtime_error(
5309 std::string("set_pressure_bottom_solver('direct'): not eligible here: ") + why);
5310 }
5311#ifdef PECLET_FLOW_MPI
5312 // The agreement directBottomIneligibleAll() reads: MAX over comm_, a rank idling below a
5313 // telescope point contributing zeros (every rank holding the bottom holds the same values: the
5314 // global dims, and gb_'s labels and planes, which are replicated).
5315 void agreeDirectBottom() {
5316 int v[7] = {0, 0, 0, 0, 0, 0, 0}, a[7];
5317 const Level& bt = lv_.back();
5318 if (!bt.tele) {
5319 long gx = gnxF_, gy = gnyF_, gz = gnzF_; // agglomerateBottom()'s coarsest global grid
5320 for (int L = 0; L + 1 < (int)lv_.size(); ++L) {
5321 gx /= lv_[L].ratio.x;
5322 gy /= lv_[L].ratio.y;
5323 gz /= lv_[L].ratio.z;
5324 }
5325 v[0] = bt.gdim.x;
5326 v[1] = bt.gdim.y;
5327 v[2] = bt.gdim.z;
5328 v[3] = (int)gx;
5329 v[4] = (int)gy;
5330 v[5] = (int)gz;
5331 v[6] = gbActive_ ? bottomLabelCode() : 0; // no gb_: a global condition already fails
5332 }
5333 MPI_Allreduce(v, a, 7, MPI_INT, MPI_MAX, comm_);
5334 dirAgreedGdim_ = C3{a[0], a[1], a[2]};
5335 dirAgreedExt_ = C3{a[3], a[4], a[5]};
5336 dirAgreedCode_ = a[6];
5337 dirAgreedKnown_ = true;
5338 }
5339#endif
5340 // The bottom's storage (§13.4.7): single rank (any backend since §14 H-1), a bottom of at most
5341 // kBottomMaxCells cells with ghost width 1; otherwise none and the engine is ineligible.
5342 // The FCG vectors, the component labels and their scratch, the plane ordering and the factor.
5344 joinPrefactor(); // X: dir_ and the bottom level are about to be replaced
5345 dirAgreedKnown_ = false; // review note 1: re-agreed at the hierarchy's first operator build
5346 dirAgreedCode_ = 1;
5347 facStale_ = true;
5348 bottomConnKnown_ = false;
5349 bottomConnected_ = false;
5350 bottomStore_ = false;
5351 dirPlanes_ = BottomPlanes{};
5352 gbActive_ = false;
5353 if (lv_.empty())
5354 return;
5355 if (distributed_ && !(kHostMemory && buildGlobalBottomLevel()))
5356 return; // §14 H-6: distributed, the store lives on the host global bottom gb_ only
5357 const Level& bt = bottomLv();
5358 if (bt.g != 1 || (long)bt.inner.x * bt.inner.y * bt.inner.z > kBottomMaxCells)
5359 return;
5360 bottomStore_ = true;
5361 for (CCField* f : {&bottomR_, &bottomP_, &bottomZ_, &bottomZp_, &bottomAp_})
5362 *f = CCField("mg_bottom_fcg", bt.n);
5363 bottomInfo_ = Kokkos::View<int*, CCMem>("peclet::flow::mg_bottom_info", 1);
5364 bottomComp_ = Kokkos::View<int*, CCMem>("peclet::flow::mg_bottom_comp", bt.n);
5365 bottomLabTmp_ = Kokkos::View<int*, CCMem>("peclet::flow::mg_bottom_labtmp", bt.n);
5366 bottomCompCnt_ =
5367 Kokkos::View<long*, CCMem>("peclet::flow::mg_bottom_compcnt", kBottomMaxComponents);
5368 bottomCompMean_ = CCField("peclet::flow::mg_bottom_compmean", kBottomMaxComponents);
5369 dirKc_ = Kokkos::View<int*, CCMem>("peclet::flow::mg_bottom_kc", kBottomMaxComponents);
5370 dirAug_ = Kokkos::View<double*, CCMem>("peclet::flow::mg_bottom_aug", kBottomMaxComponents);
5371 dirPlanes_ = bottomChoosePlanes(bt.inner, bc_);
5372 dir_ = BottomDirect<float>::allocate(dirPlanes_, bt.ext); // PRECISION-EXEMPT: §13 FP32 factor
5373 dirTeam_ = 0;
5374 dirFacTeam_ = 0;
5375 }
5376 // The level the direct bottom runs on: lv_.back() single rank, the global bottom gb_ under
5377 // §14 H-6 (distributed host).
5378 Level& bottomLv() { return gbActive_ ? gb_ : lv_.back(); }
5379 const Level& bottomLv() const { return gbActive_ ? gb_ : lv_.back(); }
5380 // §14 H-6 (doc/vof_step_performance_design.md §14.3): the distributed host 'direct' bottom runs
5381 // REDUNDANTLY on every rank that holds the bottom level, on gb_: a private, single-rank-shaped
5382 // copy of the GLOBAL bottom (g = 1, og = 0, gdim = inner) assembled from the allgathered inner
5383 // openness by the single-rank fill, boundary openness and operator build, so it equals the
5384 // single-rank bottom bitwise whenever the gathered openness does (the np-gates' hierarchy
5385 // property, which GraphAMG's gather relies on too). Returns false -- no gb_, GraphAMG stays --
5386 // on a rank idling below a telescope point and for a global bottom above kBottomMaxCells.
5387 // gbLocal_: this rank's inner cells' global ids (x fastest; gb_'s own map, never GraphAMG's
5388 // amgGlobalOfLocal_, which buildAmg rewrites); gbGid_: every bottom rank's, in gather order
5389 // (rank order, then gbLocal_ order), gathered once per hierarchy.
5391#ifdef PECLET_FLOW_MPI
5392 const Level& bt = lv_.back();
5393 if (bt.tele)
5394 return false; // this rank holds no bottom (it idles below a telescope point)
5395 const C3 gi = bt.gdim;
5396 if ((long)gi.x * gi.y * gi.z > kBottomMaxCells)
5397 return false;
5398 Level g;
5399 g.inner = gi;
5400 g.gdim = gi;
5401 g.ratio = bt.ratio;
5402 g.cfac = bt.cfac;
5403 g.g = 1;
5404 g.ext = C3{gi.x + 2, gi.y + 2, gi.z + 2};
5405 g.n = (std::size_t)g.ext.x * g.ext.y * g.ext.z;
5406 g.x = CCField("mg_gb_x", g.n);
5407 g.rhs = CCField("mg_gb_rhs", g.n);
5408 g.ox = CCField("mg_gb_ox", g.n);
5409 g.oy = CCField("mg_gb_oy", g.n);
5410 g.oz = CCField("mg_gb_oz", g.n);
5411 for (FPV* p : {&g.AC, &g.AFX, &g.AFY, &g.AFZ})
5412 *p = FPV("mg_gb_A", g.n);
5413 // this rank's inner cells -> global bottom id (buildAmg's formula and order, on bt.gdim)
5414 gbLocal_.clear();
5415 for (int k = 0; k < bt.inner.z; ++k)
5416 for (int j = 0; j < bt.inner.y; ++j)
5417 for (int i = 0; i < bt.inner.x; ++i)
5418 gbLocal_.push_back((bt.og.x + i) + (bt.og.y + j) * gi.x + (bt.og.z + k) * gi.x * gi.y);
5419 // the per-rank cell counts are fixed per hierarchy: exchanged once here, then cached for the
5420 // per-operator openness and per-V-cycle rhs gathers (review note 3)
5421 int size = 1;
5422 MPI_Comm_size(bt.comm, &size);
5423 const int nloc = (int)gbLocal_.size();
5424 gbCnt1_.assign(size, 0);
5425 MPI_Allgather(&nloc, 1, MPI_INT, gbCnt1_.data(), 1, MPI_INT, bt.comm);
5426 gbDsp1_.assign(size, 0);
5427 gbCnt3_.assign(size, 0);
5428 gbDsp3_.assign(size, 0);
5429 int tot = 0;
5430 for (int r = 0; r < size; ++r) {
5431 gbDsp1_[r] = tot;
5432 gbCnt3_[r] = 3 * gbCnt1_[r];
5433 gbDsp3_[r] = 3 * tot;
5434 tot += gbCnt1_[r];
5435 }
5436 gbGid_.resize((std::size_t)tot);
5437 MPI_Allgatherv(gbLocal_.data(), nloc, MPI_INT, gbGid_.data(), gbCnt1_.data(), gbDsp1_.data(),
5438 MPI_INT, bt.comm);
5439 gb_ = g;
5440 gbActive_ = true;
5441 return true;
5442#else
5443 return false;
5444#endif
5445 }
5446 // gb_'s extended index of global bottom id `gid` (x fastest).
5447 long gbIndex(int gid) const {
5448 const int gx = gid % gb_.inner.x, t = gid / gb_.inner.x;
5449 const int gy = t % gb_.inner.y, gz = t / gb_.inner.y;
5450 return (long)(gx + 1) + (long)(gy + 1) * gb_.ext.x + (long)(gz + 1) * gb_.ext.x * gb_.ext.y;
5451 }
5452 // §14 H-6, once per operator change (setOpenness): allgather the bottom level's inner openness
5453 // by global id into gb_, then the single-rank fillOpenness, applyBoundaryOpenness and
5454 // buildCutcellOpFace (same gf as the single-rank bottom build). An operator the direct engine
5455 // can never take (an outflow face, a non-singular operator) is not built.
5457#ifdef PECLET_FLOW_MPI
5458 if (!removeMean_ || hasOutflow_)
5459 return;
5460 // Review note 4: nor on a hierarchy where the direct bottom can never run -- no axis with
5461 // valid planes (fixed at the hierarchy build), or the first build's labels outside 1..64 (fixed
5462 // per hierarchy). Both are replicated over bt.comm (gb_ is), so the skip is rank-uniform. The
5463 // labels of a plane-less hierarchy then run on the never-built (zero) operator: no component.
5464 if (!dirPlanes_.valid() || (bottomConnKnown_ && !bottomConnected_))
5465 return;
5466 Level& bt = lv_.back();
5467 const int g = bt.g, ex = bt.ext.x, ey = bt.ext.y;
5468 auto hox = Kokkos::create_mirror_view_and_copy(Kokkos::HostSpace(), bt.ox);
5469 auto hoy = Kokkos::create_mirror_view_and_copy(Kokkos::HostSpace(), bt.oy);
5470 auto hoz = Kokkos::create_mirror_view_and_copy(Kokkos::HostSpace(), bt.oz);
5471 std::vector<double> lo;
5472 lo.reserve(3 * gbLocal_.size());
5473 for (int k = 0; k < bt.inner.z; ++k)
5474 for (int j = 0; j < bt.inner.y; ++j)
5475 for (int i = 0; i < bt.inner.x; ++i) {
5476 const long p = (long)(i + g) + (long)(j + g) * ex + (long)(k + g) * ex * ey;
5477 lo.push_back(hox(p));
5478 lo.push_back(hoy(p));
5479 lo.push_back(hoz(p));
5480 }
5481 std::vector<double> go(3 * gbGid_.size());
5482 MPI_Allgatherv(lo.data(), (int)lo.size(), MPI_DOUBLE, go.data(), gbCnt3_.data(), gbDsp3_.data(),
5483 MPI_DOUBLE, bt.comm); // the counts cached per hierarchy
5484 Level& gb = gb_;
5485 auto gox = Kokkos::create_mirror_view(gb.ox);
5486 auto goy = Kokkos::create_mirror_view(gb.oy);
5487 auto goz = Kokkos::create_mirror_view(gb.oz);
5488 for (std::size_t r = 0; r < gbGid_.size(); ++r) {
5489 const long q = gbIndex(gbGid_[r]);
5490 gox(q) = go[3 * r];
5491 goy(q) = go[3 * r + 1];
5492 goz(q) = go[3 * r + 2];
5493 }
5494 Kokkos::deep_copy(gb.ox, gox);
5495 Kokkos::deep_copy(gb.oy, goy);
5496 Kokkos::deep_copy(gb.oz, goz);
5497 fillLocal(gb, gb.ox); // the single-rank fillOpenness
5498 fillLocal(gb, gb.oy);
5499 fillLocal(gb, gb.oz);
5501 const double sx = 1.0 / (double)(gb.cfac.x * gb.cfac.x),
5502 sy = 1.0 / (double)(gb.cfac.y * gb.cfac.y),
5503 sz = 1.0 / (double)(gb.cfac.z * gb.cfac.z);
5504 buildCutcellOpFace(gb.AC, gb.AFX, gb.AFY, gb.AFZ, CCConst(gb.ox), CCConst(gb.oy),
5505 CCConst(gb.oz), gb.ext, gb.g, gfx_ * sx, gfy_ * sy, gfz_ * sz);
5506#endif
5507 }
5508 // §14 H-6, per V-cycle: allgatherv the bottom rhs (as graphAmgSolveBottom does) into gb_.rhs.
5510#ifdef PECLET_FLOW_MPI
5511 Level& bt = lv_.back();
5512 const int g = bt.g, ex = bt.ext.x, ey = bt.ext.y;
5513 auto hrhs = Kokkos::create_mirror_view_and_copy(Kokkos::HostSpace(), bt.rhs);
5514 std::vector<double> lb;
5515 lb.reserve(gbLocal_.size());
5516 for (int k = 0; k < bt.inner.z; ++k)
5517 for (int j = 0; j < bt.inner.y; ++j)
5518 for (int i = 0; i < bt.inner.x; ++i)
5519 lb.push_back(hrhs((long)(i + g) + (long)(j + g) * ex + (long)(k + g) * ex * ey));
5520 std::vector<double> gbv(gbGid_.size());
5521 MPI_Allgatherv(lb.data(), (int)lb.size(), MPI_DOUBLE, gbv.data(), gbCnt1_.data(),
5522 gbDsp1_.data(), MPI_DOUBLE, bt.comm); // the counts cached per hierarchy
5523 auto grhs = Kokkos::create_mirror_view(gb_.rhs);
5524 for (std::size_t r = 0; r < gbGid_.size(); ++r)
5525 grhs(gbIndex(gbGid_[r])) = gbv[r];
5526 Kokkos::deep_copy(gb_.rhs, grhs);
5527#endif
5528 }
5529 // §14 H-6, per V-cycle: this rank's block of gb_.x into the bottom level's x (ghosts 0, as
5530 // graphAmgSolveBottom leaves them).
5532 Level& bt = lv_.back();
5533 const int g = bt.g, ex = bt.ext.x, ey = bt.ext.y;
5534 auto hgx = Kokkos::create_mirror_view_and_copy(Kokkos::HostSpace(), gb_.x);
5535 auto hx = Kokkos::create_mirror_view(bt.x);
5536 Kokkos::deep_copy(hx, 0.0);
5537 std::size_t c = 0;
5538 for (int k = 0; k < bt.inner.z; ++k)
5539 for (int j = 0; j < bt.inner.y; ++j)
5540 for (int i = 0; i < bt.inner.x; ++i)
5541 hx((long)(i + g) + (long)(j + g) * ex + (long)(k + g) * ex * ey) =
5542 hgx(gbIndex(gbLocal_[c++]));
5543 Kokkos::deep_copy(bt.x, hx);
5544 }
5545 // Condition 6, as B1b replaced it (§5.14): the bottom level's fluid components, labelled on the
5546 // device by BottomLabelKernel -- eligible with 1..64 of them (the register's per-component
5547 // projector for the agglomerated bottom; more go to GraphAMG) -- and, along the slow axis, each
5548 // component's last plane and 1/m_c (§13.4.2). One team launch and one scalar read, at the first
5549 // operator build of a hierarchy (geometry time; the rho / eps / drag rescaling of the per-step
5550 // setOpenness never closes or opens a face, so the labels stay valid).
5552 bottomConnKnown_ = true;
5553 bottomConnected_ = false;
5554 bottomNComp_ = 0;
5555 if (!bottomStore_)
5556 return;
5557 const Level& bt = bottomLv();
5559 k.ext = bt.ext;
5560 k.inner = bt.inner;
5561 k.AC = bt.AC;
5562 k.AFX = bt.AFX;
5563 k.AFY = bt.AFY;
5564 k.AFZ = bt.AFZ;
5565 k.comp = bottomComp_;
5566 k.tmp = bottomLabTmp_;
5567 k.cnt = bottomCompCnt_;
5568 k.nc = bottomInfo_; // info(0) doubles as the component-count landing slot here
5569 k.slow = dirPlanes_.s;
5570 k.kc = dirKc_;
5571 k.aug = dirAug_;
5572 Kokkos::TeamPolicy<CCExec> probe(CCExec(), 1, 1);
5573 const int T = std::min(1024, probe.team_size_max(k, Kokkos::ParallelForTag()));
5574 Kokkos::parallel_for("peclet::flow::mg_bottom_label",
5575 Kokkos::TeamPolicy<CCExec>(CCExec(), 1, T), k);
5576 Kokkos::deep_copy(bottomNComp_, Kokkos::subview(bottomInfo_, 0));
5577 bottomConnected_ = bottomNComp_ >= 1 && bottomNComp_ <= kBottomMaxComponents;
5578 if (mgDebugLevel())
5579 printf("[mg] device bottom: %d fluid component(s) on the %dx%dx%d bottom%s\n", bottomNComp_,
5580 bt.inner.x, bt.inner.y, bt.inner.z,
5581 bottomConnected_ ? "" : " -> GraphAMG (more than 64, or none)");
5582 }
5583 template <class FR = float> // PRECISION-EXEMPT: the FP32 direct factor under an FP64 FCG
5585 ensureScalars();
5586 Level& bt = bottomLv();
5588 k.lv.ext = bt.ext;
5589 k.lv.inner = bt.inner;
5590 k.lv.AC = bt.AC;
5591 k.lv.AFX = bt.AFX;
5592 k.lv.AFY = bt.AFY;
5593 k.lv.AFZ = bt.AFZ;
5594 k.x = bt.x;
5595 k.b = bt.rhs;
5596 k.r = bottomR_;
5597 k.p = bottomP_;
5598 k.z = bottomZ_;
5599 k.zp = bottomZp_;
5600 k.ap = bottomAp_;
5601 k.precondOnly = precondOnly ? 1 : 0;
5602 k.ks = ks_;
5603 k.flagSlot = kBottomFlag;
5604 k.info = bottomInfo_;
5605 k.nc = bottomNComp_;
5606 k.comp = bottomComp_;
5607 k.ccnt = bottomCompCnt_;
5608 k.cmean = bottomCompMean_;
5609 return k;
5610 }
5611 // A non-finite scalar in a device bottom solve (the kernel's device flag) fails the solve. `v`
5612 // is the flag as read by the PCG packet or by lastSolveFailed(); a set flag is cleared on the
5613 // device so it is reported once.
5614 void noteBottomFlag(double v) {
5615 bottomFlagPending_ = false;
5616 if (v != 0.0) {
5617 solveFailed_ = true;
5618 setSlot(kBottomFlag, 0.0);
5619 }
5620 }
5621 // A launch's team size: min(1024, team_size_max) when team <= 0 -- min(hostTeam,
5622 // team_size_max) on a host backend (§14 H-1) -- else `team` clamped to team_size_max; with
5623 // `probe` false a positive `team` (a size this kernel already ran with) is used as is.
5624 // `scratch` = the team scratch (level 0) the kernel requests, in bytes.
5625 template <class K>
5626 static int directTeam(const K& k, int team, bool probe, std::size_t scratch = 0,
5627 int hostTeam = kBottomHostTeam) {
5628 if (team > 0 && !probe)
5629 return team;
5630 Kokkos::TeamPolicy<CCExec> pol(CCExec(), 1, 1);
5631 if (scratch)
5632 pol.set_scratch_size(0, Kokkos::PerTeam(scratch));
5633 const int tmax = std::min(1024, pol.team_size_max(k, Kokkos::ParallelForTag()));
5634 if (team > 0)
5635 return std::min(team, tmax);
5636 return kHostMemory ? std::min(hostTeam, tmax) : tmax;
5637 }
5638 // The factor launch: one team, T = directTeam(team) (the U3 hook passes T; the factor is bitwise
5639 // independent of it). `teamAlgorithm` (a test hook, U8) runs the team algorithm on a host
5640 // backend instead of the host schedule. Returns the team size used.
5641 template <class FR>
5642 int launchDirectFactor(const BottomDirect<FR>& D, int team, double tauPiv0, bool probe = true,
5643 bool teamAlgorithm = false, const CCExec& exec = CCExec()) {
5644 const Level& bt = bottomLv();
5646 k.D = D;
5647 k.AFX = bt.AFX;
5648 k.AFY = bt.AFY;
5649 k.AFZ = bt.AFZ;
5650 k.comp = bottomComp_;
5651 k.kc = dirKc_;
5652 k.aug = dirAug_;
5653 k.tauPiv0 = tauPiv0;
5654 k.teamAlgorithm = teamAlgorithm ? 1 : 0;
5655#ifdef PECLET_FLOW_BOTTOM_PROBE
5656 if (bottomProbe_.extent(0) == 0)
5657 bottomProbe_ = Kokkos::View<long long*, CCMem>("peclet::flow::mg_bottom_probe", 16);
5658 k.probe = bottomProbe_;
5659#endif
5660 const std::size_t scratch = BottomFactorKernel<FR, FPC>::scratchBytes(D.pl.b);
5661 const int T = directTeam(k, team, probe, scratch, kBottomHostFactorTeam);
5662 Kokkos::parallel_for(
5663 "peclet::flow::mg_bottom_factor",
5664 Kokkos::TeamPolicy<CCExec>(exec, 1, T).set_scratch_size(0, Kokkos::PerTeam(scratch)), k);
5665 return T;
5666 }
5667 // The FCG kernel with M = the direct factor `D`: the production solve (precondOnly = false) or,
5668 // for the tests, z = M(lv.rhs) alone. Returns the team size used.
5669 template <class FR>
5670 int launchDirectKernel(const BottomDirect<FR>& D, bool precondOnly, int team, bool noMean,
5671 CCField zOut = CCField(), CCField rIn = CCField(), bool probe = true,
5672 bool teamAlgorithm = false) {
5673 BottomKernel<FR> k = makeBottomKernel<FR>(precondOnly);
5674 k.dir = D;
5675 k.noMeanForTest = noMean ? 1 : 0;
5676 k.teamAlgorithm = teamAlgorithm ? 1 : 0;
5677 if (precondOnly) {
5678 k.z = zOut;
5679 k.b = rIn;
5680 }
5681 const int T = directTeam(k, team, probe);
5682 Kokkos::parallel_for("peclet::flow::mg_bottom_direct",
5683 Kokkos::TeamPolicy<CCExec>(CCExec(), 1, T), k);
5684 return T;
5685 }
5686 // X (doc/vof_gpu_coarse_tail_design.md §5.6): the factor on a side execution instance. The
5687 // solver builds the variable-rho coefficients right after updateProperties() and calls
5688 // prefactorBottom(), which launches the factor of the new operator on `side_` (a second CUDA
5689 // stream from partition_space) while the momentum stage runs on the default instance;
5690 // joinPrefactor() fences `side_` before anything reads dir_ or writes the bottom operator (the
5691 // bottom solve, setOpenness, buildBottomStore, the test hooks, the destructor). Same kernel,
5692 // same inputs, same T rule: the factor is bitwise the lazy one. Device single rank only.
5694 if constexpr (kHostMemory) {
5695 return false;
5696 } else {
5697 return !distributed_ && bottomStore_ && bottomSolver_ != kBottomAlgebraic &&
5698 directBottomIneligible() == nullptr;
5699 }
5700 }
5702 if (!directPrefactorEligible() || !facStale_)
5703 return;
5704 if constexpr (!kHostMemory) {
5705 if (!side_)
5706 side_ = Kokkos::Experimental::partition_space(CCExec(), std::vector<int>{1})[0];
5707 CCExec().fence("peclet::flow::mg_prefactor_ready"); // the operator build has landed
5708 dirFacTeam_ =
5709 launchDirectFactor(dir_, dirFacTeam_, dirPivotTol_, /*probe=*/false, false, *side_);
5710 facStale_ = false;
5711 facPending_ = true;
5712 ++prefactorLaunches_;
5713 }
5714 }
5715 // Side-instance factors launched so far (diagnostics: the WO-X hoist fired).
5716 long prefactorLaunches() const { return prefactorLaunches_; }
5717 bool joinPrefactor() const {
5718 if (!facPending_)
5719 return false;
5720 side_->fence("peclet::flow::mg_prefactor_join");
5721 facPending_ = false;
5722 return true;
5723 }
5725 // The production direct bottom solve: lv.x = A_b^{-1} lv.rhs (component-mean-free) by the FCG
5726 // preconditioned by the FP32 factor, refactored first if setOpenness changed the operator (a
5727 // host flag, not a device read).
5729 const bool first = dirTeam_ == 0;
5730 bool factored = joinPrefactor(); // X: the side-instance factor of this operator has landed
5731 if (gbActive_)
5732 gatherGlobalBottomRhs(); // §14 H-6: every rank solves the identical global bottom
5733 if (facStale_) {
5734 dirFacTeam_ = launchDirectFactor(dir_, dirFacTeam_, dirPivotTol_, /*probe=*/false);
5735 facStale_ = false;
5736 factored = true;
5737 }
5738 if (factored) {
5739 if (mgDebugLevel() >= 2 && dbgSolve_ <= mgDebugSolves()) {
5740 auto h = Kokkos::create_mirror_view_and_copy(Kokkos::HostSpace(), dir_.stat);
5741 printf("[mg] direct bottom factor: ok %d, restarts %d (team %d)\n", h(0), h(1),
5742 dirFacTeam_);
5743 }
5744 }
5745 dirTeam_ =
5746 launchDirectKernel(dir_, false, dirTeam_, false, CCField(), CCField(), /*probe=*/false);
5747 if (gbActive_)
5748 scatterGlobalBottomX(); // each rank copies its own block of x out
5749 if (first && mgDebugLevel()) {
5750 printf(
5751 "[mg] direct bottom: %dx%dx%d, slow axis %d, P = %d, b = %d, border %d; team sizes "
5752 "factor %d, solve %d\n",
5753 bottomLv().inner.x, bottomLv().inner.y, bottomLv().inner.z, dirPlanes_.s, dirPlanes_.P,
5754 dirPlanes_.b, dirPlanes_.border, dirFacTeam_, dirTeam_);
5755 fflush(stdout);
5756 }
5757 bottomFlagPending_ = true;
5758 if (mgDebugLevel() >= 2 && dbgSolve_ <= mgDebugSolves()) {
5759 int it = 0;
5760 Kokkos::deep_copy(it, Kokkos::subview(bottomInfo_, 0));
5761 printf("[mg] direct bottom: %d inner iterations (team %d)\n", it, dirTeam_);
5762 }
5763 }
5764
5765 // --- Agglomerated GraphAMG bottom solve --------------------------------------------------------
5766 // Assemble the coarsest level's cut-cell operator as a GLOBAL CSR (gathered to rank 0) and build
5767 // a mesh-agnostic smoothed-aggregation AMG on it. Decomposition-agnostic: the CSR is keyed by
5768 // GLOBAL cell id (periodic-wrapped neighbours), so any (weighted) ORB gives the SAME operator.
5769 void buildAmg(Level& lv) {
5770 const C3 gb = amgBottomDims();
5771 amgGlobalN_ = gb.x * gb.y * gb.z;
5772 const AmgRows local = amgLocalRows(lv, gb);
5773 amgGlobalOfLocal_ = local.gid;
5774 // all-gather every rank's rows (no-op / identity single-rank): EVERY rank assembles the same
5775 // global CSR and builds the same AMG (redundant coarse solve).
5776 AmgRows rows = local;
5777#ifdef PECLET_FLOW_MPI
5778 if (distributed_)
5779 gatherAmgRows(local, rows, lv.comm);
5780#endif
5781 amgLabelComponents(rows);
5782 if (agmgDebug())
5783 printAmgBuildCensus(rows);
5784 peclet::core::solver::HostCsrOp A = amgAssembleCsr(rows);
5785 amgA_ = A;
5786 amg_ = std::make_shared<peclet::core::solver::GraphAMG>();
5787 amg_->build(A);
5788 }
5789 // buildAmg's operator as rows before the CSR assembly: per cell its global id, diagonal and
5790 // solid (identity-row) marker; per off-diagonal coupling its row gid, column gid and value.
5791 // One rank's rows (amgLocalRows), or every rank's after gatherAmgRows.
5792 struct AmgRows {
5793 std::vector<int> gid, row, col;
5794 std::vector<double> diag, val;
5795 std::vector<std::uint8_t> solid; // AGMG_DEBUG: identity-row marker, per row
5796 };
5797 // The bottom level's GLOBAL dims: the fine dims coarsened by every ratio above it.
5799 int gbx = gnxF_, gby = gnyF_, gbz = gnzF_;
5800 for (int L = 0; L + 1 < (int)lv_.size(); ++L) {
5801 gbx /= lv_[L].ratio.x;
5802 gby /= lv_[L].ratio.y;
5803 gbz /= lv_[L].ratio.z;
5804 }
5805 return C3{gbx, gby, gbz};
5806 }
5807 // This rank's rows of the bottom operator (inner cells in x-fastest order), periodic-wrapped by
5808 // GLOBAL id on the bottom grid gb.
5809 AmgRows amgLocalRows(const Level& lv, C3 gb) const {
5810 const int gbx = gb.x, gby = gb.y;
5811 const int nx = lv.inner.x, ny = lv.inner.y, nz = lv.inner.z, ex = lv.ext.x, ey = lv.ext.y;
5812 auto host = [](FPV v) {
5813 auto h = Kokkos::create_mirror_view(v);
5814 Kokkos::deep_copy(h, v);
5815 return h;
5816 };
5817 auto hC = host(lv.AC), hAFX = host(lv.AFX), hAFY = host(lv.AFY), hAFZ = host(lv.AFZ);
5818 AmgRows o;
5819 const int g = lv.g;
5820 for (int k = 0; k < nz; ++k)
5821 for (int j = 0; j < ny; ++j)
5822 for (int i = 0; i < nx; ++i) {
5823 const long p = (long)(i + g) + (long)(j + g) * ex + (long)(k + g) * ex * ey;
5824 const C3 gc{lv.og.x + i, lv.og.y + j, lv.og.z + k};
5825 const int gid = gc.x + gc.y * gbx + gc.z * gbx * gby;
5826 o.gid.push_back(gid);
5827 // solid cells (all faces closed => diag 0, no coupling) get an identity row so D^-1 is
5828 // finite; their rhs is 0, so x stays 0 (correct — no flow inside the solid).
5829 const double dc = (double)hC(p);
5830 o.diag.push_back(dc != 0.0 ? dc : 1.0);
5831 o.solid.push_back(dc == 0.0 ? 1 : 0);
5832 // A2 face form: AW = AFX(p), AE = AFX(p+1), ... (the band values themselves).
5833 const double bc[6] = {(double)hAFX(p), (double)hAFX(p + 1),
5834 (double)hAFY(p), (double)hAFY(p + ex),
5835 (double)hAFZ(p), (double)hAFZ(p + (long)ex * ey)};
5836 amgCellCouplings(gc, gb, gid, bc, o);
5837 }
5838 return o;
5839 }
5840 // The off-diagonal couplings of the cell at GLOBAL index gc (row gid, face coefficients bc in
5841 // the order -x, +x, -y, +y, -z, +z), appended to o.
5842 void amgCellCouplings(C3 gc, C3 gb, int gid, const double (&bc)[6], AmgRows& o) const {
5843 const int band[6][3] = {{-1, 0, 0}, {1, 0, 0}, {0, -1, 0}, {0, 1, 0}, {0, 0, -1}, {0, 0, 1}};
5844 const int gbx = gb.x, gby = gb.y, gbz = gb.z;
5845 for (int d = 0; d < 6; ++d) {
5846 if (bc[d] == 0.0)
5847 continue; // closed face (wall) -> no coupling
5848 // A face crossing the domain boundary couples to the wrapped cell ONLY on a periodic
5849 // axis (bc_ type 0). On a non-periodic axis an OPEN boundary face is the Dirichlet
5850 // outflow anchor: its coefficient lives in the diagonal (already in AC) with NO
5851 // off-diagonal partner — wrapping it would add a spurious top<->bottom coupling and
5852 // (with the mean projection skipped) a wrong, possibly indefinite bottom matrix.
5853 const int rx = gc.x + band[d][0], ry = gc.y + band[d][1], rz = gc.z + band[d][2];
5854 const int axis = d / 2;
5855 const bool crosses = (axis == 0 && (rx < 0 || rx >= gbx)) ||
5856 (axis == 1 && (ry < 0 || ry >= gby)) ||
5857 (axis == 2 && (rz < 0 || rz >= gbz));
5858 if (crosses && bc_[d] != 0)
5859 continue; // non-periodic boundary face: Dirichlet anchor stays diagonal-only
5860 const int ngx = (rx % gbx + gbx) % gbx;
5861 const int ngy = (ry % gby + gby) % gby;
5862 const int ngz = (rz % gbz + gbz) % gbz;
5863 o.row.push_back(gid);
5864 o.col.push_back(ngx + ngy * gbx + ngz * gbx * gby);
5865 o.val.push_back(bc[d]);
5866 }
5867 }
5868#ifdef PECLET_FLOW_MPI
5869 // Every rank's rows, all-gathered in rank order (field by field: gid, diag, row, col, val,
5870 // solid).
5871 void gatherAmgRows(const AmgRows& local, AmgRows& all, MPI_Comm c) {
5872 gatherv(local.gid, all.gid, c);
5873 gatherv(local.diag, all.diag, c);
5874 gatherv(local.row, all.row, c);
5875 gatherv(local.col, all.col, c);
5876 gatherv(local.val, all.val, c);
5877 gatherv(local.solid, all.solid, c);
5878 }
5879#endif
5880 // amgSolid_ per gid, and the connected components of the operator graph (union-find over the
5881 // off-diagonal edges): each FLUID component carries its own constant null vector, so the
5882 // null-space projection must be per-component. Solid identity rows are singletons and take no
5883 // projection.
5884 void amgLabelComponents(const AmgRows& rows) {
5885 amgSolid_.assign((std::size_t)amgGlobalN_, 0);
5886 for (std::size_t r = 0; r < rows.gid.size(); ++r)
5887 amgSolid_[(std::size_t)rows.gid[r]] = rows.solid[r];
5888 std::vector<int> parent((std::size_t)amgGlobalN_);
5889 for (int i = 0; i < amgGlobalN_; ++i)
5890 parent[(std::size_t)i] = i;
5891 auto find = [&](int a) {
5892 while (parent[(std::size_t)a] != a)
5893 a = parent[(std::size_t)a] = parent[(std::size_t)parent[(std::size_t)a]];
5894 return a;
5895 };
5896 for (std::size_t e = 0; e < rows.row.size(); ++e) {
5897 const int ra = find(rows.row[e]), rb = find(rows.col[e]);
5898 if (ra != rb)
5899 parent[(std::size_t)ra] = rb;
5900 }
5901 amgComp_.assign((std::size_t)amgGlobalN_, -1);
5902 std::vector<int> remap((std::size_t)amgGlobalN_, -1);
5903 amgNComp_ = 0;
5904 for (int i = 0; i < amgGlobalN_; ++i) {
5905 if (amgSolid_[(std::size_t)i])
5906 continue; // identity row: no null space, excluded from projection
5907 const int r = find(i);
5908 if (remap[(std::size_t)r] < 0)
5909 remap[(std::size_t)r] = amgNComp_++;
5910 amgComp_[(std::size_t)i] = remap[(std::size_t)r];
5911 }
5912 }
5913 // PECLET_FLOW_AGMG_DEBUG census of the gathered bottom operator: component sizes, the fluid
5914 // diagonal range and the row-sum defect.
5915 void printAmgBuildCensus(const AmgRows& rows) const {
5916 std::vector<long> csize((std::size_t)amgNComp_, 0);
5917 for (int i = 0; i < amgGlobalN_; ++i)
5918 if (amgComp_[(std::size_t)i] >= 0)
5919 ++csize[(std::size_t)amgComp_[(std::size_t)i]];
5920 printf("[agmg-build] fluid components=%d sizes:", amgNComp_);
5921 for (int c = 0; c < std::min(amgNComp_, 12); ++c)
5922 printf(" %ld", csize[(std::size_t)c]);
5923 printf(amgNComp_ > 12 ? " ...\n" : "\n");
5924 long nSolid = 0, nTiny30 = 0, nTiny12 = 0;
5925 double minFluidDiag = 1e300, maxFluidDiag = 0;
5926 for (std::size_t r = 0; r < rows.gid.size(); ++r) {
5927 if (rows.solid[r]) {
5928 ++nSolid;
5929 continue;
5930 }
5931 const double ad = std::fabs(rows.diag[r]);
5932 minFluidDiag = std::min(minFluidDiag, ad);
5933 maxFluidDiag = std::max(maxFluidDiag, ad);
5934 nTiny30 += ad < 1e-30;
5935 nTiny12 += ad < 1e-12;
5936 }
5937 printf(
5938 "[agmg-build] n=%d solid=%ld fluid=%ld fluid|diag| min=%.3e max=%.3e "
5939 "tiny<1e-30=%ld <1e-12=%ld\n",
5940 amgGlobalN_, nSolid, (long)rows.gid.size() - nSolid, minFluidDiag, maxFluidDiag, nTiny30,
5941 nTiny12);
5942 // Row-sum defect: the operator's null vector is the constant ONLY if every fluid row sums
5943 // to zero. The level coefficients are stored in float (MReal), so the diagonal is a
5944 // float-rounded sum of the face coefficients — a nonzero defect here bounds how far a
5945 // singular-consistent solve can converge.
5946 std::vector<double> rowsum((std::size_t)amgGlobalN_, 0.0);
5947 for (std::size_t r = 0; r < rows.gid.size(); ++r)
5948 rowsum[(std::size_t)rows.gid[r]] = rows.solid[r] ? 0.0 : rows.diag[r];
5949 for (std::size_t e = 0; e < rows.row.size(); ++e)
5950 if (!amgSolid_[(std::size_t)rows.row[e]])
5951 rowsum[(std::size_t)rows.row[e]] += rows.val[e];
5952 double defMax = 0, defRelMax = 0;
5953 for (std::size_t r = 0; r < rows.gid.size(); ++r)
5954 if (!rows.solid[r]) {
5955 const double d = std::fabs(rowsum[(std::size_t)rows.gid[r]]);
5956 defMax = std::max(defMax, d);
5957 defRelMax = std::max(defRelMax, d / std::fabs(rows.diag[r]));
5958 }
5959 printf("[agmg-build] fluid row-sum defect max=%.3e rel=%.3e\n", defMax, defRelMax);
5960 fflush(stdout);
5961 }
5962 // The global CSR keyed by gid, from the gathered rows.
5963 peclet::core::solver::HostCsrOp amgAssembleCsr(const AmgRows& rows) const {
5964 peclet::core::solver::HostCsrOp A;
5965 A.n = amgGlobalN_;
5966 A.diag.assign((std::size_t)amgGlobalN_, 0.0);
5967 for (std::size_t r = 0; r < rows.gid.size(); ++r)
5968 A.diag[(std::size_t)rows.gid[r]] = rows.diag[r];
5969 std::vector<std::vector<std::pair<int, double>>> crow((std::size_t)amgGlobalN_);
5970 for (std::size_t e = 0; e < rows.row.size(); ++e)
5971 crow[(std::size_t)rows.row[e]].push_back({rows.col[e], rows.val[e]});
5972 A.start.assign((std::size_t)amgGlobalN_ + 1, 0);
5973 for (int r = 0; r < amgGlobalN_; ++r)
5974 A.start[(std::size_t)r + 1] = A.start[(std::size_t)r] + (long)crow[(std::size_t)r].size();
5975 A.nbr.reserve(rows.row.size());
5976 A.coef.reserve(rows.row.size());
5977 for (int r = 0; r < amgGlobalN_; ++r)
5978 for (auto& [c, v] : crow[(std::size_t)r]) {
5979 A.nbr.push_back(c);
5980 A.coef.push_back(v);
5981 }
5982 // Singular (periodic / all-Neumann) path: every fluid diagonal is BY CONSTRUCTION the
5983 // negative sum of its off-diagonals (walls/solids contribute zero, and no Dirichlet anchor
5984 // exists when removeMean_). The float (MReal) level storage breaks that identity at ~5e-8
5985 // relative, which shifts the operator's near-null vector off the constant the null-space
5986 // projection assumes — measured as the inner CG flooring at ~1e-5 and burning its full
5987 // iteration cap every call. Resum the diagonal in double so A·1 = 0 EXACTLY per fluid row.
5988 if (removeMean_)
5989 for (int r = 0; r < amgGlobalN_; ++r)
5990 if (!amgSolid_[(std::size_t)r] && !crow[(std::size_t)r].empty()) {
5991 double s = 0;
5992 for (auto& [c, v] : crow[(std::size_t)r])
5993 s += v;
5994 A.diag[(std::size_t)r] = -s;
5995 }
5996 return A;
5997 }
5998 // Solve the coarsest level with the agglomerated AMG, REDUNDANTLY: all-gather the coarse rhs,
5999 // every rank runs the identical GraphAMG-preconditioned CG on the identical global operator
6000 // (deterministic serial code on identical data => bit-identical solutions), and each extracts
6001 // its own block — one Allgatherv per V-cycle, no rank-0 serialization, no result broadcast.
6003 if (!amg_ && !distributed_)
6004 buildAmg(lv);
6005#ifdef PECLET_FLOW_MPI
6006 if (distributed_ && amgGlobalN_ == 0)
6007 buildAmg(lv);
6008#endif
6009 const int nx = lv.inner.x, ny = lv.inner.y, nz = lv.inner.z, ex = lv.ext.x, ey = lv.ext.y;
6010 const int g = lv.g;
6011 auto hrhs = Kokkos::create_mirror_view(lv.rhs);
6012 Kokkos::deep_copy(hrhs, lv.rhs);
6013 std::vector<double> lb;
6014 lb.reserve(amgGlobalOfLocal_.size());
6015 for (int k = 0; k < nz; ++k)
6016 for (int j = 0; j < ny; ++j)
6017 for (int i = 0; i < nx; ++i)
6018 lb.push_back((double)hrhs((long)(i + g) + (long)(j + g) * ex + (long)(k + g) * ex * ey));
6019 // all-gather rhs by global id -> b; every rank solves the identical problem.
6020 std::vector<double> z((std::size_t)std::max(amgGlobalN_, 1), 0.0);
6021#ifdef PECLET_FLOW_MPI
6022 if (distributed_) {
6023 std::vector<int> ggid;
6024 std::vector<double> gb;
6025 gatherv(amgGlobalOfLocal_, ggid, lv.comm);
6026 gatherv(lb, gb, lv.comm);
6027 std::vector<double> b((std::size_t)amgGlobalN_, 0.0);
6028 for (std::size_t r = 0; r < ggid.size(); ++r)
6029 b[(std::size_t)ggid[r]] = gb[r];
6030 pcgAmg(b, z);
6031 } else
6032#endif
6033 {
6034 std::vector<double> b(lb.begin(), lb.end());
6035 pcgAmg(b, z);
6036 }
6037 // scatter z[gid] back into this rank's inner cells.
6038 auto hx = Kokkos::create_mirror_view(lv.x);
6039 Kokkos::deep_copy(hx, 0.0);
6040 std::size_t c = 0;
6041 for (int k = 0; k < nz; ++k)
6042 for (int j = 0; j < ny; ++j)
6043 for (int i = 0; i < nx; ++i)
6044 hx((long)(i + g) + (long)(j + g) * ex + (long)(k + g) * ex * ey) =
6045 z[(std::size_t)amgGlobalOfLocal_[c++]];
6046 Kokkos::deep_copy(lv.x, hx);
6047 if (agmgDebug() && !distributed_) {
6048 // Consistency check: the CSR solution must satisfy the V-cycle's OWN bottom operator
6049 // (ghost fill + outflow ghost + 7-point apply). A large residual here means buildAmg
6050 // assembled a DIFFERENT matrix than the one the hierarchy applies.
6051 fill(lv, lv.x);
6052 applyOutflowGhost(lv, lv.x, lv.g);
6053 residualCutcellFace(lv.res, CCConst(lv.x), CCConst(lv.rhs), FPC(lv.AC), FPC(lv.AFX),
6054 FPC(lv.AFY), FPC(lv.AFZ), lv.ext, lv.g);
6055 const double rn = maxabs(lv, lv.res);
6056 auto hb = Kokkos::create_mirror_view(lv.rhs);
6057 Kokkos::deep_copy(hb, lv.rhs);
6058 double bn = 0;
6059 for (std::size_t i = 0; i < hb.size(); ++i)
6060 bn = std::max(bn, std::fabs((double)hb(i)));
6061 printf("[agmg] vcycle-op residual of CSR solution: max|b-Ax|=%.3e max|b|=%.3e rel=%.3e\n",
6062 rn, bn, bn > 0 ? rn / bn : 0.0);
6063 fflush(stdout);
6064 }
6065 }
6066 // pcgAmg's rhs anatomy (PECLET_FLOW_AGMG_DEBUG), BEFORE the null-space projection (b is
6067 // gid-ordered): max|b| over the solid and the fluid rows, the fluid and all-row means, and the
6068 // max per-component |sum(b)| / |b|_max (the per-pocket incompatibility).
6070 double bSolidMax = 0, bFluidMax = 0, bFluidMean = 0, bAllMean = 0, bCompMax = 0;
6071 };
6072 AmgRhsAnatomy amgRhsAnatomy(const std::vector<double>& b) const {
6073 const std::size_t n = (std::size_t)amgGlobalN_;
6074 AmgRhsAnatomy a;
6075 long nf = 0;
6076 double sf = 0, sa = 0;
6077 for (std::size_t i = 0; i < n; ++i) {
6078 sa += b[i];
6079 if (i < amgSolid_.size() && amgSolid_[i])
6080 a.bSolidMax = std::max(a.bSolidMax, std::fabs(b[i]));
6081 else {
6082 a.bFluidMax = std::max(a.bFluidMax, std::fabs(b[i]));
6083 sf += b[i];
6084 ++nf;
6085 }
6086 }
6087 a.bFluidMean = nf ? sf / (double)nf : 0.0;
6088 a.bAllMean = n ? sa / (double)n : 0.0;
6089 if (amgNComp_ > 1) {
6090 std::vector<double> cs((std::size_t)amgNComp_, 0.0);
6091 for (std::size_t i = 0; i < n; ++i)
6092 if (amgComp_[i] >= 0)
6093 cs[(std::size_t)amgComp_[i]] += b[i];
6094 for (double s : cs)
6095 a.bCompMax = std::max(a.bCompMax, std::fabs(s));
6096 a.bCompMax /= (a.bFluidMax > 0 ? a.bFluidMax : 1.0);
6097 }
6098 return a;
6099 }
6100 // pcgAmg's null-space projection of v: the mean of each connected fluid component.
6101 void amgMeanZero(std::vector<double>& v) const {
6102 if (!removeMean_)
6103 return; // Dirichlet-anchored (outflow) operator: non-singular, no null space to project
6104 // The null space is one constant PER CONNECTED FLUID COMPONENT — solid cells are identity
6105 // rows (non-singular) and a coarse level can pinch fluid off into pockets, each carrying its
6106 // own constant. Projecting the ALL-cell mean out instead (the old code) both leaves null
6107 // components alive and writes a spurious value onto every solid coordinate; the next matvec
6108 // (identity rows) feeds that back into the residual, the effective preconditioner turns
6109 // nonsymmetric, and the inner CG stalls at its iteration cap (measured on random_spheres:
6110 // every bottom solve capped at 200 with relres up to ~1, +41% outer iterations).
6111 if (amgNComp_ <= 0)
6112 return;
6113 const std::size_t n = (std::size_t)amgGlobalN_;
6114 std::vector<double> m((std::size_t)amgNComp_, 0.0);
6115 std::vector<long> cnt((std::size_t)amgNComp_, 0);
6116 for (std::size_t i = 0; i < n; ++i)
6117 if (amgComp_[i] >= 0) {
6118 m[(std::size_t)amgComp_[i]] += v[i];
6119 ++cnt[(std::size_t)amgComp_[i]];
6120 }
6121 for (std::size_t c = 0; c < m.size(); ++c)
6122 m[c] = cnt[c] ? m[c] / (double)cnt[c] : 0.0;
6123 for (std::size_t i = 0; i < n; ++i)
6124 if (amgComp_[i] >= 0)
6125 v[i] -= m[(std::size_t)amgComp_[i]];
6126 }
6127 // pcgAmg's dot product over the first n entries, in index order.
6128 static double amgDot(const std::vector<double>& a, const std::vector<double>& c, std::size_t n) {
6129 double s = 0;
6130 for (std::size_t i = 0; i < n; ++i)
6131 s += a[i] * c[i];
6132 return s;
6133 }
6134 // pcgAmg's per-call report (PECLET_FLOW_AGMG_DEBUG; every call at level 2, else the first 60,
6135 // every 50th and every capped one): iterations, relative residual, the rhs anatomy and max|x|
6136 // over the solid and the fluid rows.
6137 void amgReport(const AmgRhsAnatomy& a, const std::vector<double>& x, const std::vector<double>& r,
6138 int it, double r0, int dbg) {
6139 const std::size_t n = (std::size_t)amgGlobalN_;
6140 double xSolidMax = 0, xFluidMax = 0;
6141 for (std::size_t i = 0; i < n; ++i)
6142 if (i < amgSolid_.size() && amgSolid_[i])
6143 xSolidMax = std::max(xSolidMax, std::fabs(x[i]));
6144 else
6145 xFluidMax = std::max(xFluidMax, std::fabs(x[i]));
6146 const double rn = std::sqrt(amgDot(r, r, n));
6147 ++agmgCalls_;
6148 if (dbg >= 2 || agmgCalls_ <= 60 || it >= 100 || agmgCalls_ % 50 == 0) {
6149 printf(
6150 "[agmg] call=%ld iters=%d relres=%.2e |b|sol=%.3e |b|fl=%.3e "
6151 "mean(b) fl=%.3e all=%.3e compat=%.2e |x|sol=%.3e |x|fl=%.3e%s\n",
6152 agmgCalls_, it, r0 > 0 ? rn / r0 : 0.0, a.bSolidMax, a.bFluidMax, a.bFluidMean,
6153 a.bAllMean, a.bCompMax, xSolidMax, xFluidMax, it >= 100 ? " CAP" : "");
6154 fflush(stdout);
6155 }
6156 }
6157 // GraphAMG-preconditioned CG on the global bottom operator. For the periodic/all-Neumann case the
6158 // operator is singular (constant null space) and the mean must be projected out of the rhs and
6159 // the preconditioned residual (compatibility). With a Dirichlet outflow (removeMean_ == false)
6160 // the operator is NON-singular and the projection must be SKIPPED — removing the constant from a
6161 // non-singular system returns a wrong bottom correction and the V-cycle around it diverges.
6162 // Runs on rank 0 only.
6163 void pcgAmg(std::vector<double>& b, std::vector<double>& x) {
6164 const std::size_t n = (std::size_t)amgGlobalN_;
6165 const int dbg = agmgDebug();
6166 const AmgRhsAnatomy rhs = dbg ? amgRhsAnatomy(b) : AmgRhsAnatomy{};
6167 amgMeanZero(b);
6168 x.assign(n, 0.0);
6169 std::vector<double> r = b, z(n), p(n), Ap(n);
6170 amg_->apply(r, z);
6171 amgMeanZero(z);
6172 p = z;
6173 double rz = amgDot(r, z, n), r0 = std::sqrt(amgDot(r, r, n));
6174 // 1e-8 is deliberate: the V-cycle's outer iteration count is unchanged from a far looser
6175 // bottom (measured), while 1e-10 sits at/below the double-precision floor of this
6176 // projected solve (rounding of the per-iteration null-space projection), where CG grinds
6177 // out its full iteration cap for nothing.
6178 int it = 0;
6179 for (; it < 100 && r0 > 0; ++it) {
6180 amgA_.apply(p, Ap);
6181 // CG breakdown guard (core's GraphAMG pcg has the same one): p^T A p = 0 means the search
6182 // direction lies in the null space, i.e. the projected rhs has no range component left and
6183 // x is already the answer. It happens when the bottom rhs is round-off on a constant: the
6184 // projection's rounded mean differs from the value by an ulp and leaves an exactly CONSTANT
6185 // residual (8 x -0x1.ffffffffffffcp-103 -> 8 x 0x1p-154 on the uniform periodic porous bed),
6186 // the AMG maps it to z = 0, and rz / pAp = 0/0 poisoned x with NaN, which the outer PCG then
6187 // reported as a non-finite preconditioner and a CAPPED solve.
6188 const double pAp = amgDot(p, Ap, n);
6189 if (!(pAp > 0.0))
6190 break;
6191 const double a = rz / pAp;
6192 for (std::size_t i = 0; i < n; ++i) {
6193 x[i] += a * p[i];
6194 r[i] -= a * Ap[i];
6195 }
6196 if (std::sqrt(amgDot(r, r, n)) <= 1e-8 * r0)
6197 break;
6198 amg_->apply(r, z);
6199 amgMeanZero(z);
6200 const double rzn = amgDot(r, z, n);
6201 const double beta = rzn / rz;
6202 rz = rzn;
6203 for (std::size_t i = 0; i < n; ++i)
6204 p[i] = z[i] + beta * p[i];
6205 }
6206 amgMeanZero(x);
6207 if (dbg)
6208 amgReport(rhs, x, r, it, r0, dbg);
6209 }
6210#ifdef PECLET_FLOW_MPI
6211 template <class T>
6212 void gatherv(const std::vector<T>& local, std::vector<T>& all, MPI_Comm c) {
6213 // REDUNDANT agglomeration: every rank receives the full concatenation (rank order, so the
6214 // assembled coarse problem is bit-identical on all ranks and each solves it locally with no
6215 // rank-0 bottleneck and no result broadcast).
6216 int size = 1;
6217 MPI_Comm_size(c, &size);
6218 const int lbytes = (int)(local.size() * sizeof(T));
6219 std::vector<int> bc(size), bd(size, 0);
6220 MPI_Allgather(&lbytes, 1, MPI_INT, bc.data(), 1, MPI_INT, c);
6221 int tot = 0;
6222 for (int r = 0; r < size; ++r) {
6223 bd[r] = tot;
6224 tot += bc[r];
6225 }
6226 all.resize((std::size_t)tot / sizeof(T));
6227 MPI_Allgatherv(local.data(), lbytes, MPI_BYTE, all.data(), bc.data(), bd.data(), MPI_BYTE, c);
6228 }
6229#endif
6230
6231 // Level-0 matvec with the halo overlapped: post the exchange, apply the interior rows while the
6232 // messages are in flight, land the ghosts (+ outflow ghost), apply the boundary shell. Reads v,
6233 // writes y (no aliasing) => bit-identical to the blocking fill-then-apply. Single-rank: the
6234 // blocking path.
6236 const bool ex = exactResidual_; // P1: exact double flux-form apply instead of the bands
6237 if (!ex)
6238 ensureFp64(); // D5 (§4.4.7): the band apply reads level 0's AFX, AFY, AFZ
6239#ifdef PECLET_FLOW_MPI
6240 if (distributed_) {
6241 const int m = stencilWrap(l0); // K3 (§5.2), as in smooth()
6242 const C3 lo = boxLo(G, m), hi = boxHi(l0.ext, G, m);
6243 auto apply = [&](C3 rlo, C3 rhi, C3 slo, C3 shi) {
6244 if (ex)
6246 l0.ext, rlo, rhi, slo, shi, gfx_, gfy_, gfz_, m, G);
6247 else
6248 applyCutcellOpBoxFace(y, CCConst(v), FPC(l0.AC), FPC(l0.AFX), FPC(l0.AFY), FPC(l0.AFZ),
6249 l0.ext, rlo, rhi, slo, shi, m, G);
6250 };
6251 if (m == 7) {
6252 apply(lo, hi, C3{0, 0, 0}, C3{0, 0, 0});
6253 return;
6254 }
6255 GridHalo<double>& h = stencilHalo(l0);
6256 h.exchangeBegin(v);
6257 apply(lo, hi, C3{0, 0, 0}, C3{0, 0, 0});
6258 h.exchangeEnd(v);
6259 applyOutflowGhost(l0, v);
6260 apply(C3{G, G, G}, C3{l0.ext.x - G, l0.ext.y - G, l0.ext.z - G}, lo, hi);
6261 return;
6262 }
6263#endif
6264 if (fusedWrapReads()) { // A3: the matvec reads the periodic wrap directly, no fill
6265 if (ex)
6267 l0.ext, l0.inner, G, gfx_, gfy_, gfz_);
6268 else
6269 applyCutcellOpFaceWrap(y, CCConst(v), FPC(l0.AC), FPC(l0.AFX), FPC(l0.AFY), FPC(l0.AFZ),
6270 l0.ext, l0.inner, G);
6271 return;
6272 }
6273 fill(l0, v);
6274 applyOutflowGhost(l0, v);
6275 if (ex)
6276 applyCutcellOpExact(y, CCConst(v), CCConst(l0.ox), CCConst(l0.oy), CCConst(l0.oz), l0.ext, G,
6277 gfx_, gfy_, gfz_);
6278 else
6279 applyCutcellOpFace(y, CCConst(v), FPC(l0.AC), FPC(l0.AFX), FPC(l0.AFY), FPC(l0.AFZ), l0.ext,
6280 G);
6281 }
6282 // periodic ghost fill (3 axes) of a level-sized field / the openness triple. Distributed: the
6283 // per-level core halo (cross-rank + periodic in one call).
6284 void fill(Level& lv, CCField f) {
6285#ifdef PECLET_FLOW_MPI
6286 if (distributed_) {
6287 lv.dev->exchange(f);
6288 return;
6289 }
6290#endif
6291 fillLocal(lv, f);
6292 }
6293 // The single-rank ghost fill of a level field (the periodic wrap copy); under MPI also the
6294 // §14 H-6 global bottom gb_'s, which is single-rank-shaped on every rank.
6295 void fillLocal(Level& lv, CCField f) {
6296 if (lv.inner.x < lv.g || lv.inner.y < lv.g || lv.inner.z < lv.g) {
6297 // a ghost band wider than the block: the sequential passes copy ghost from ghost, which the
6298 // one-shot wrap does not reproduce -- keep them
6299 fillAxis(lv, f, 0);
6300 fillAxis(lv, f, 1);
6301 fillAxis(lv, f, 2);
6302 return;
6303 }
6304 fillWrap(lv, f);
6305 }
6306 // D-dist (doc/vof_projection_distributed_design.md §5.3): the ghost fill of an FP32 level field.
6307 // Distributed: the level's GridHalo<float> (cross-rank + periodic, as fill() for a CCField);
6308 // single rank: the periodic wrap copy (the FP32 levels are even, so the one-shot wrap holds).
6309 void fill(Level& lv, VField f) {
6310#ifdef PECLET_FLOW_MPI
6311 if (distributed_) {
6312 lv.devf->exchange(f);
6313 return;
6314 }
6315#endif
6316 fillWrap(lv, f);
6317 }
6318 // The single-rank periodic fill in ONE launch over the ghost shell: every ghost cell takes the
6319 // value of the inner cell its three coordinates wrap to. That is exactly what the three
6320 // sequential `fillAxis` passes (x, then y, then z, each over the full transverse extent, ghosts
6321 // included) leave behind -- a ghost already written by an earlier pass is overwritten by the
6322 // later pass with the wrapped-inner value, and inner cells are only ever read -- so the two are
6323 // bit-identical (pure copies). The V-cycle calls this before every smoother colour, so the three
6324 // launches it replaces were two thirds of the solve's kernel launches, and on the coarse levels
6325 // the launch, not the copy, is the cost.
6326 template <class V> // CCField; D: also the FP32 coarse iterate (VField), the same copies
6327 void fillWrap(Level& lv, V f) {
6328 CCExec space;
6329 const C3 e = lv.ext;
6330 const int G = lv.g; // shadows the class constant: this level's ghost width
6331 const int nx = lv.inner.x, ny = lv.inner.y, nz = lv.inner.z;
6332 const long exy = (long)e.x * e.y;
6333 // the shell as three slabs: z-ghost planes (all x, y), then y-ghost rows of the inner z range
6334 // (all x), then x-ghost cells of the inner (y, z) range
6335 const long nZ = 2L * G * exy, nY = (long)nz * 2 * G * e.x, nX = (long)nz * ny * 2 * G;
6336 if constexpr (std::is_same_v<typename CCExec::memory_space, Kokkos::HostSpace>) {
6337 // A3 (§4.3, §5.4): on a host backend the same three slabs go ROW by row -- the index math
6338 // (one division) per row, a contiguous copy along x inside it -- serially below the cutoff.
6339 // The one-thread-per-cell form below paid a 64-bit div/mod per ghost cell (85 us per
6340 // launch at 24 threads). Every ghost cell is still written once, from the inner cell its
6341 // three coordinates wrap to, so the result is identical. No simd mark: a row's source and
6342 // destination can share the row (the x-ghost slab).
6343 const long rZ = 2L * G * e.y, rY = (long)nz * 2 * G, rX = (long)nz * ny;
6344 V ff = f;
6345 auto copyRow = [=](long dst, long src) { // one full x row, wrapped along x
6346 for (int x = 0; x < G; ++x)
6347 ff(dst + x) = ff(src + x + nx);
6348 for (int x = G; x < G + nx; ++x)
6349 ff(dst + x) = ff(src + x);
6350 for (int x = G + nx; x < e.x; ++x)
6351 ff(dst + x) = ff(src + x - nx);
6352 };
6353 auto row = [=](long t) {
6354 if (t < rZ) { // z-ghost plane row (y, zg)
6355 const int l = (int)(t / e.y), y = (int)(t - (long)l * e.y);
6356 const int z = l < G ? l : nz + l;
6357 const int sy = y < G ? y + ny : (y >= G + ny ? y - ny : y);
6358 const int sz = z < G ? z + nz : z - nz;
6359 copyRow((long)y * e.x + (long)z * exy, (long)sy * e.x + (long)sz * exy);
6360 } else if (t < rZ + rY) { // y-ghost row (yg, z) of the inner z range
6361 const long t2 = t - rZ;
6362 const int zi = (int)(t2 / (2 * G)), l = (int)(t2 - (long)zi * 2 * G);
6363 const int y = l < G ? l : ny + l, z = G + zi;
6364 const int sy = y < G ? y + ny : y - ny;
6365 copyRow((long)y * e.x + (long)z * exy, (long)sy * e.x + (long)z * exy);
6366 } else { // the x-ghost cells of inner row (y, z)
6367 const long t3 = t - rZ - rY;
6368 const int zi = (int)(t3 / ny), yi = (int)(t3 - (long)zi * ny);
6369 const long base = (long)(G + yi) * e.x + (long)(G + zi) * exy;
6370 for (int x = 0; x < G; ++x)
6371 ff(base + x) = ff(base + x + nx);
6372 for (int x = G + nx; x < e.x; ++x)
6373 ff(base + x) = ff(base + x - nx);
6374 }
6375 };
6376 if (hostRunSerial(nZ + nY + nX)) {
6377 const HostSerialRegion serialRegion("peclet::flow::mg_pfill3@serial"); // WO-T
6378 for (long t = 0; t < rZ + rY + rX; ++t)
6379 row(t);
6380 return;
6381 }
6382 Kokkos::parallel_for("peclet::flow::mg_pfill3",
6383 Kokkos::RangePolicy<CCExec>(space, 0, rZ + rY + rX), row);
6384 return;
6385 }
6386 V ff = f;
6387 Kokkos::parallel_for(
6388 "peclet::flow::mg_pfill3", Kokkos::RangePolicy<CCExec>(space, 0, nZ + nY + nX),
6389 KOKKOS_LAMBDA(long t) {
6390 int x, y, z;
6391 if (t < nZ) {
6392 const int l = (int)(t / exy);
6393 const long r = t - (long)l * exy;
6394 x = (int)(r % e.x);
6395 y = (int)(r / e.x);
6396 z = l < G ? l : nz + l;
6397 } else if (t < nZ + nY) {
6398 const long t2 = t - nZ, row = 2L * G * e.x;
6399 const long zi = t2 / row, r = t2 - zi * row;
6400 const int l = (int)(r / e.x);
6401 x = (int)(r % e.x);
6402 y = l < G ? l : ny + l;
6403 z = G + (int)zi;
6404 } else {
6405 const long t3 = t - nZ - nY, row = (long)ny * 2 * G;
6406 const long zi = t3 / row, r = t3 - zi * row;
6407 const int l = (int)(r % (2 * G));
6408 x = l < G ? l : nx + l;
6409 y = G + (int)(r / (2 * G));
6410 z = G + (int)zi;
6411 }
6412 const int sx = x < G ? x + nx : (x >= G + nx ? x - nx : x);
6413 const int sy = y < G ? y + ny : (y >= G + ny ? y - ny : y);
6414 const int sz = z < G ? z + nz : (z >= G + nz ? z - nz : z);
6415 ff((long)x + (long)y * e.x + (long)z * exy) =
6416 ff((long)sx + (long)sy * e.x + (long)sz * exy);
6417 });
6418 }
6420 fill(lv, lv.ox);
6421 fill(lv, lv.oy);
6422 fill(lv, lv.oz);
6423 }
6424 void fillAxis(Level& lv, CCField f, int axis) {
6425 CCExec space;
6426 C3 e = lv.ext;
6427 const int G = lv.g; // shadows the class constant: this level's ghost width
6428 int N3[3] = {lv.inner.x, lv.inner.y, lv.inner.z};
6429 int dims[3] = {e.x, e.y, e.z};
6430 long st[3] = {1, e.x, (long)e.x * e.y};
6431 const int a = axis, b = (axis + 1) % 3, c = (axis + 2) % 3;
6432 const long sa = st[a], sb = st[b], sc = st[c];
6433 const int N = N3[a];
6434 CCField ff = f;
6435 Kokkos::parallel_for(
6436 "peclet::flow::mg_pfill", MDRange2<CCExec>(space, {0, 0}, {dims[b], dims[c]}),
6437 KOKKOS_LAMBDA(int p0, int p1) {
6438 const long base = (long)p0 * sb + (long)p1 * sc;
6439 for (int gl = 0; gl < G; ++gl) {
6440 ff(base + (long)gl * sa) = ff(base + (long)(gl + N) * sa);
6441 ff(base + (long)(G + N + gl) * sa) = ff(base + (long)(G + gl) * sa);
6442 }
6443 });
6444 }
6445#ifdef PECLET_FLOW_MPI
6446 // ghost-projection matvec staging (solveBiCGStab distributed): copy the l0 inner cells onto the
6447 // caller's g=2 block (whose halo then carries the overlay's +/-2 reach) ...
6448 void stageG2(Level& l0, CCField q, CCField xg2, C3 ext2) {
6449 CCExec space;
6450 const C3 e1 = l0.ext, nn = l0.inner;
6451 CCField dst = xg2, src = q;
6452 Kokkos::parallel_for(
6453 "peclet::flow::gp_stage_g2", MDRange3<CCExec>(space, {0, 0, 0}, {nn.x, nn.y, nn.z}),
6454 KOKKOS_LAMBDA(int x, int y, int z) {
6455 dst((long)(x + 2) + (long)(y + 2) * ext2.x + (long)(z + 2) * (long)ext2.x * ext2.y) =
6456 src((long)(x + G) + (long)(y + G) * e1.x + (long)(z + G) * (long)e1.x * e1.y);
6457 });
6458 }
6459 // ... and read the whole l0 block (inner + its g=1 ring) back from the exchanged g=2 copy, so
6460 // the 7-point op's halo is current without a second exchange.
6461 void unstageG2(Level& l0, CCField q, CCField xg2) {
6462 CCExec space;
6463 const C3 e1 = l0.ext;
6464 const C3 ext2{e1.x + 2, e1.y + 2, e1.z + 2}; // same inner, gb 1 -> 2
6465 CCField dst = q, src = xg2;
6466 Kokkos::parallel_for(
6467 "peclet::flow::gp_unstage_g2", MDRange3<CCExec>(space, {0, 0, 0}, {e1.x, e1.y, e1.z}),
6468 KOKKOS_LAMBDA(int x, int y, int z) {
6469 dst((long)x + (long)y * e1.x + (long)z * (long)e1.x * e1.y) =
6470 src((long)(x + 1) + (long)(y + 1) * ext2.x + (long)(z + 1) * (long)ext2.x * ext2.y);
6471 });
6472 }
6473#endif
6474 void axpy(CCField y, double a, CCField x) {
6475 CCExec space;
6476 CCField yy = y, xx = x;
6477 std::size_t n = y.extent(0);
6478 Kokkos::parallel_for(
6479 "mgaxpy", Kokkos::RangePolicy<CCExec>(space, 0, n),
6480 KOKKOS_LAMBDA(std::size_t i) { yy(i) += a * xx(i); });
6481 }
6482 void aypx(CCField y, double a, CCField x) {
6483 CCExec space;
6484 CCField yy = y, xx = x;
6485 std::size_t n = y.extent(0);
6486 Kokkos::parallel_for(
6487 "mgaypx", Kokkos::RangePolicy<CCExec>(space, 0, n),
6488 KOKKOS_LAMBDA(std::size_t i) { yy(i) = xx(i) + a * yy(i); });
6489 }
6490 void scale(CCField y, double a) {
6491 CCExec space;
6492 CCField yy = y;
6493 std::size_t n = y.extent(0);
6494 Kokkos::parallel_for(
6495 "mgscale", Kokkos::RangePolicy<CCExec>(space, 0, n),
6496 KOKKOS_LAMBDA(std::size_t i) { yy(i) *= a; });
6497 }
6498 void lin(CCField out, double a, CCField x, double b, CCField y) { // out = a*x + b*y (mg_lin_k)
6499 CCExec space;
6500 CCField oo = out, xx = x, yy = y;
6501 std::size_t n = out.extent(0);
6502 Kokkos::parallel_for(
6503 "mglin", Kokkos::RangePolicy<CCExec>(space, 0, n),
6504 KOKKOS_LAMBDA(std::size_t i) { oo(i) = a * xx(i) + b * yy(i); });
6505 }
6506 // zero the solid-cell entries (AC<=tiny) -> project out the solid null modes (mg_mask_solid_k).
6507 void maskSolid(Level& lv, CCField f) {
6508 CCExec space;
6509 CCField ff = f;
6510 FPV ac = lv.AC;
6511 std::size_t n = f.extent(0);
6512 Kokkos::parallel_for(
6513 "mgmasksolid", Kokkos::RangePolicy<CCExec>(space, 0, n), KOKKOS_LAMBDA(std::size_t i) {
6514 if (!(ac(i) > 1e-30f))
6515 ff(i) = 0.0;
6516 });
6517 }
6518
6519 // f += amp * h(global cell) over the inner cells, h a fixed hash of the GLOBAL cell index into
6520 // [-0.5, 0.5): the same value at a cell whatever the decomposition (np-independent by
6521 // construction). The cold eigenvalue seed's broadband component (see estimateEigenvalues).
6522 void addSeedNoise(Level& lv, CCField f, double amp) {
6523 CCExec space;
6524 const C3 e = lv.ext, og = lv.og;
6525 const int g = lv.g;
6526 CCField ff = f;
6527 Kokkos::parallel_for(
6528 "peclet::flow::mg_seed_noise",
6529 MDRange3<CCExec>(space, {g, g, g}, {e.x - g, e.y - g, e.z - g}),
6530 KOKKOS_LAMBDA(int x, int y, int z) {
6531 std::uint64_t h = (std::uint64_t)(og.x + x - g) * 0x9E3779B97F4A7C15ull ^
6532 (std::uint64_t)(og.y + y - g) * 0xC2B2AE3D27D4EB4Full ^
6533 (std::uint64_t)(og.z + z - g) * 0x165667B19E3779F9ull;
6534 h ^= h >> 30; // splitmix64 finaliser
6535 h *= 0xBF58476D1CE4E5B9ull;
6536 h ^= h >> 27;
6537 h *= 0x94D049BB133111EBull;
6538 h ^= h >> 31;
6539 const long i = (long)x + (long)y * e.x + (long)z * (long)e.x * e.y;
6540 ff(i) += amp * ((double)(h >> 11) * 0x1.0p-53 - 0.5);
6541 });
6542 }
6543
6544 // A zero-filled level-0 work vector that persists across solves: the Chebyshev driver and its
6545 // eigenvalue estimate used to allocate (and free) eight of these per step -- a
6546 // cudaMalloc/cudaFree pair each, and cudaFree synchronises the device. Same contents as a fresh
6547 // View (zeros), so the solves are unchanged bit for bit.
6548 CCField workVector(int slot, std::size_t n, const char* label) {
6549 CCField& v = work_[slot];
6550 if (v.extent(0) != n)
6551 v = CCField(label, n);
6552 else
6553 Kokkos::deep_copy(CCExec(), v, 0.0);
6554 return v;
6555 }
6556
6557 // How estimateEigenvalues starts its two power iterations (D3, doc/vof_step_performance_design.md
6558 // §5.13). `Cold`: both from `seed` (the right-hand side), nothing kept -- the pre-D3 estimate,
6559 // and still the balanced-force pre-projection's. `ColdKeep`: the same arithmetic, and the last
6560 // v_max / v_min iterates are kept. `Warm`: each iteration starts from its kept iterate (masked,
6561 // mean-removed and normalised exactly as the rhs seed is) and the kept iterates are replaced by
6562 // the new last ones; `seed` is not read. Warm requires eigenWarmReady().
6563 enum class EigenStart { Cold, ColdKeep, Warm };
6564 // Symmetric V-cycle only: the factor on the lambda_max estimate that SHIFTS the min power
6565 // iteration (see estimateEigenvalues). The returned lambda_max stays the raw estimate.
6566 static constexpr double kChebSymShift = 1.15;
6567 // The bracketing upper margin of the re-estimate after a cold-bounds Chebyshev solve tripped
6568 // its growth guard (estimateEigenvalues' `bracket`): lambda_max is returned as 1.15 x the
6569 // estimate, which brackets every top measured over the ctest battery (worst 1.129 x the
6570 // Euclidean estimate, doc/mg_depth_policy_log.md 2026-10-29).
6571 static constexpr double kChebBracket = 1.15;
6572 // True when a ColdKeep or Warm estimate has run on the current hierarchy (init/initMpi drop it).
6573 bool eigenWarmReady() const {
6574 return eigWarm_ && !lv_.empty() && eigVmax_.extent(0) == lv_[0].n &&
6575 eigVmin_.extent(0) == lv_[0].n;
6576 }
6577 // The kept iterates are cross-step state: the Solver's `redistribute` carries them across a
6578 // repartition (inner cells migrated like a registry field) and hands them back here.
6579 CCField eigenWarmMax() const { return eigVmax_; }
6580 CCField eigenWarmMin() const { return eigVmin_; }
6581 void setEigenWarm(CCField vmax, CCField vmin) {
6582 eigVmax_ = vmax;
6583 eigVmin_ = vmin;
6584 eigWarm_ = true;
6585 }
6586
6587 // The cold lambda_max estimate of the symmetric V-cycle ((c), DECISIONS_GPU.log 2026-10-30 "A3
6588 // finish"; PETSc KSPChebyshev's estimate): kLanczosSteps steps of PCG on A x = b from x = 0,
6589 // b = `v` (the seed, normalised), preconditioned by the symmetric V-cycle M. PCG is Lanczos on
6590 // M^{1/2} A M^{1/2}; its coefficients give the tridiagonal T_m (diagonal 1/alpha_j +
6591 // beta_{j-1}/alpha_{j-1}, off-diagonal sqrt(beta_j)/alpha_j), whose eigenvalues are the Ritz
6592 // values of M^{-1} A. Returns the top one; it stops early once that changes by less than
6593 // kLanczosTol (relative). The Ritz values lie inside the spectrum and the top converges at
6594 // the Krylov rate, not the power iteration's geometric one. With `ritz` the same PCG run is
6595 // repeated (identical arithmetic) to accumulate the top Ritz vector sum_j y_j (-1)^j
6596 // z_j / sqrt(r_j . z_j) into `v` (normalised), the warm estimates' seed; else `v` is left as
6597 // given. Work: m V-cycles and m matvecs (twice with `ritz`), two reductions per step.
6598 static constexpr int kLanczosSteps = 10;
6599 static constexpr double kLanczosTol = 1e-3;
6600 double lanczosTop(Level& l0, CCField v, bool ritz) {
6601 const std::size_t n = l0.n;
6602 CCField w = workVector(1, n, "ev_w"), z = workVector(2, n, "ev_z"),
6603 r = workVector(4, n, "lz_r"), p = workVector(5, n, "lz_p");
6604 auto precondP = [&](CCField zz, CCField rr) { // z = M r on the fluid range (applyT's)
6605 precondVcycle(zz, rr);
6606 removeMean(l0, zz);
6607 maskSolid(l0, zz);
6608 };
6609 double alpha[kLanczosSteps], beta[kLanczosSteps], rhoj[kLanczosSteps];
6610 auto tridiag = [&](int m, double* d, double* e) {
6611 for (int j = 0; j < m; ++j) {
6612 d[j] = 1.0 / alpha[j] + (j > 0 ? beta[j - 1] / alpha[j - 1] : 0.0);
6613 e[j] = j + 1 < m ? std::sqrt(beta[j]) / alpha[j] : 0.0;
6614 }
6615 };
6616 // One PCG pass. mFixed = 0: adaptive (stop on the top Ritz value), returns m and the top.
6617 // mFixed > 0: the repeat -- accumulate acc += c[j] z_j for j < mFixed and stop.
6618 auto pass = [&](int mFixed, const double* c, CCField acc, double& top) {
6619 Kokkos::deep_copy(CCExec(), r, v);
6620 precondP(z, r);
6621 double rho = dot(l0, r, z);
6622 Kokkos::deep_copy(CCExec(), p, z);
6623 double prev = 0.0;
6624 int m = 0;
6625 top = 0.0;
6626 for (int k = 0; k < kLanczosSteps; ++k) {
6627 if (!(rho > 0.0))
6628 break;
6629 if (mFixed > 0) {
6630 axpy(acc, c[k], z);
6631 if (k + 1 == mFixed)
6632 break;
6633 } else
6634 rhoj[k] = rho;
6635 matvecOverlap(l0, w, p);
6636 const double pAp = dot(l0, p, w);
6637 if (!(pAp > 0.0))
6638 break;
6639 alpha[k] = rho / pAp;
6640 if (mFixed == 0) {
6641 m = k + 1;
6642 double d[kLanczosSteps], e[kLanczosSteps];
6643 tridiag(m, d, e);
6644 top = symTridiagTop(m, d, e, nullptr);
6645 if ((k > 0 && std::fabs(top - prev) < kLanczosTol * top) || m == kLanczosSteps)
6646 break;
6647 prev = top;
6648 }
6649 axpy(r, -alpha[k], w);
6650 removeMean(l0, r);
6651 precondP(z, r);
6652 const double rhoNew = dot(l0, r, z);
6653 beta[k] = rhoNew / rho;
6654 rho = rhoNew;
6655 lin(p, 1.0, z, beta[k], p); // p = z + beta p
6656 }
6657 return m;
6658 };
6659 double top = 0.0;
6660 const int m = pass(0, nullptr, CCField(), top);
6661 if (ritz && m > 0) {
6663 tridiag(m, d, e);
6664 symTridiagTop(m, d, e, y);
6665 for (int j = 0; j < m; ++j)
6666 c[j] = ((j & 1) ? -y[j] : y[j]) / std::sqrt(rhoj[j]);
6667 CCField u = workVector(6, n, "lz_u");
6668 double unused = 0.0;
6669 pass(m, c, u, unused);
6670 Kokkos::deep_copy(CCExec(), v, u);
6671 const double nr = std::sqrt(dot(l0, v, v));
6672 if (nr > 0)
6673 scale(v, 1.0 / nr);
6674 }
6675 return top;
6676 }
6677 // The largest eigenvalue of the symmetric tridiagonal (d[0..m-1], off-diagonal e[0..m-2]),
6678 // m <= kLanczosSteps, by cyclic Jacobi on the dense matrix (host, deterministic); with `y`
6679 // its unit eigenvector.
6680 static double symTridiagTop(int m, const double* d, const double* e, double* y) {
6681 double A[kLanczosSteps][kLanczosSteps] = {}, V[kLanczosSteps][kLanczosSteps] = {};
6682 for (int i = 0; i < m; ++i) {
6683 A[i][i] = d[i];
6684 V[i][i] = 1.0;
6685 if (i + 1 < m)
6686 A[i][i + 1] = A[i + 1][i] = e[i];
6687 }
6688 for (int sweep = 0; sweep < 60; ++sweep) {
6689 double off = 0.0, nrm = 0.0;
6690 for (int i = 0; i < m; ++i)
6691 for (int j = 0; j < m; ++j)
6692 (i == j ? nrm : off) += A[i][j] * A[i][j];
6693 if (!(off > 1e-30 * nrm))
6694 break;
6695 for (int pq = 0; pq < m; ++pq)
6696 for (int q = pq + 1; q < m; ++q) {
6697 if (A[pq][q] == 0.0)
6698 continue;
6699 const double th = 0.5 * (A[q][q] - A[pq][pq]) / A[pq][q];
6700 const double t = (th >= 0 ? 1.0 : -1.0) / (std::fabs(th) + std::sqrt(th * th + 1.0));
6701 const double c = 1.0 / std::sqrt(t * t + 1.0), sn = t * c;
6702 for (int k = 0; k < m; ++k) { // A = J^T A J, columns then rows
6703 const double akp = A[k][pq], akq = A[k][q];
6704 A[k][pq] = c * akp - sn * akq;
6705 A[k][q] = sn * akp + c * akq;
6706 }
6707 for (int k = 0; k < m; ++k) {
6708 const double apk = A[pq][k], aqk = A[q][k];
6709 A[pq][k] = c * apk - sn * aqk;
6710 A[q][k] = sn * apk + c * aqk;
6711 }
6712 for (int k = 0; k < m; ++k) {
6713 const double vkp = V[k][pq], vkq = V[k][q];
6714 V[k][pq] = c * vkp - sn * vkq;
6715 V[k][q] = sn * vkp + c * vkq;
6716 }
6717 }
6718 }
6719 int top = 0;
6720 for (int i = 1; i < m; ++i)
6721 if (A[i][i] > A[top][top])
6722 top = i;
6723 if (y)
6724 for (int i = 0; i < m; ++i)
6725 y[i] = V[i][top];
6726 return m > 0 ? A[top][top] : 0.0;
6727 }
6728
6729 // estimateEigenvalues' seed when cold: the right-hand side plus a broadband, np-independent
6730 // component of the same max amplitude (doc/mg_depth_policy_log.md 2026-10-29): a right-hand side
6731 // confined to an invariant subspace of M^{-1}A (an x-y-uniform hydrostatic load) otherwise hides
6732 // the top of the spectrum from the power iteration, and the symmetric V-cycle's top lies above 1.
6733 void eigSeedRhs(Level& l0, CCField srhs, CCConst seed) {
6734 Kokkos::deep_copy(CCExec(), srhs, seed);
6735 if (symVcycle_) { // off: the pre-A3 estimate bit for bit (A3.3 item 4)
6736 const double sm = maxabs(l0, srhs);
6737 addSeedNoise(l0, srhs, sm > 0.0 ? sm : 1.0);
6738 }
6739 }
6740 // estimateEigenvalues' T = M^{-1} A: out = M^{-1} A in, projected onto the fluid range; w = A in
6741 // is left for the Rayleigh quotient.
6742 void eigApplyT(Level& l0, CCField out, CCField in, CCField w) {
6743 matvecOverlap(l0, w, in);
6744 precondVcycle(out, w); // A5
6745 removeMean(l0, out);
6746 maskSolid(l0, out);
6747 }
6748 // x / |x|; returns |x|.
6749 double eigNormalize(Level& l0, CCField x) {
6750 double nr = std::sqrt(dot(l0, x, x));
6751 if (nr > 0)
6752 scale(x, 1.0 / nr);
6753 return nr;
6754 }
6755 // x = src onto the fluid range, normalized; returns its norm before.
6756 double eigSeed(Level& l0, CCField x, CCField src) {
6757 Kokkos::deep_copy(CCExec(), x, src);
6758 removeMean(l0, x);
6759 maskSolid(l0, x);
6760 return eigNormalize(l0, x);
6761 }
6762 // Keeps x in dst (allocated at n cells on first use): a later warm estimate's seed.
6763 void eigKeep(CCField& dst, CCField x, const char* label, std::size_t n) {
6764 if (dst.extent(0) != n)
6765 dst = CCField(label, n);
6766 Kokkos::deep_copy(CCExec(), dst, x);
6767 }
6768 // estimateEigenvalues' power iteration for lambda_max from v (iters steps; 1 with none); v
6769 // leaves as the last iterate.
6770 double eigPowerMax(Level& l0, CCField v, CCField w, CCField z, int iters) {
6771 double lmax = 1.0;
6772 for (int k = 0; k < iters; ++k) {
6773 eigApplyT(l0, z, v, w);
6774 if (symVcycle_) {
6775 // T = M^{-1} A is self-adjoint in the A inner product when M is symmetric, so the
6776 // Rayleigh quotient is taken there: (Av . Tv) / (Av . v), w = A v as eigApplyT left it,
6777 // both sums in ONE reduction. It never exceeds lambda_max and its error is quadratic in
6778 // the iterate's; the Euclidean v . Tv is not a Rayleigh quotient of this T (with it the
6779 // true top reached 1.129 x the estimate, doc/mg_depth_policy_log.md 2026-10-29/30).
6780 double wz = 0.0, wv = 0.0;
6781 dotPair(l0, w, z, v, wz, wv);
6782 lmax = wv > 0.0 ? wz / wv : 0.0;
6783 } else { // the trilinear V-cycle (M not symmetric): the pre-A3 estimate bit for bit
6784 lmax = dot(l0, v, z);
6785 }
6786 Kokkos::deep_copy(CCExec(), v, z);
6787 eigNormalize(l0, v);
6788 }
6789 return lmax;
6790 }
6791 // estimateEigenvalues' shifted power iteration on shift*I - T from v (iters steps); returns the
6792 // Rayleigh quotient mu (0 with none), v leaving as the last iterate.
6793 double eigPowerMin(Level& l0, CCField v, CCField w, CCField z, int iters, double shift) {
6794 double mu = 0.0;
6795 for (int k = 0; k < iters; ++k) {
6796 eigApplyT(l0, z, v, w);
6797 lin(z, shift, v, -1.0, z); // z = shift*v - T v
6798 mu = dot(l0, v, z);
6799 Kokkos::deep_copy(CCExec(), v, z);
6800 eigNormalize(l0, v);
6801 }
6802 return mu;
6803 }
6804 // estimateEigenvalues' bounds from the direct (max) and shifted (min) Rayleigh estimates: a
6805 // robust min/max bracket with lmin >= 0.02 lmax, then the one-shot test hook's scale.
6806 void eigBracket(double shift, double mu, double& lmin, double& lmax) {
6807 double e_hi = lmax, e_lo = shift - mu; // direct (max) + shifted (min) Rayleigh estimates
6808 lmin = e_lo < e_hi ? e_lo : e_hi;
6809 lmax = e_lo < e_hi ? e_hi : e_lo; // robust min/max bracket
6810 if (lmin < 0.02 * lmax)
6811 lmin = 0.02 * lmax;
6812 if (dbgEigScale_ != 1.0) { // test hook (debugSetEigenScale): one estimate only
6813 lmin *= dbgEigScale_;
6814 lmax *= dbgEigScale_;
6815 dbgEigScale_ = 1.0;
6816 }
6817 }
6818 // Estimate the spectral bounds [lmin,lmax] of M^{-1}A (M^{-1} = one symmetric V-cycle) by power
6819 // iteration (direct for the max + a shifted iteration for the min), seeded by `seed` (or, with
6820 // EigenStart::Warm, by the iterates a previous estimate kept). Communication-heavy, so the CUDA
6821 // driver runs it once on step 1 and reuses the bounds. Port of estimate_eigenvalues.
6822 // `bracket` > 1 (the growth guard's re-estimate, kChebBracket): lambda_max is returned as
6823 // bracket x the estimate, and the min iteration is shifted at least that far. 1 = unchanged.
6824 void estimateEigenvalues(CCConst seed, double& lmin, double& lmax, int iters, int pre, int post,
6825 int bottom, EigenStart start = EigenStart::Cold, double bracket = 1.0) {
6826 solveFailed_ = false; // ISSUES sweep item 6: per-solve breakdown flag
6827 ++eigenEstimates_;
6828 pre_ = pre;
6829 post_ = post;
6830 bottom_ = bottom;
6831 Level& l0 = lv_[0];
6832 const std::size_t n = l0.n;
6833 CCField v = workVector(0, n, "ev_v"), w = workVector(1, n, "ev_w"),
6834 z = workVector(2, n, "ev_z"), srhs = workVector(3, n, "ev_srhs");
6835 const bool warm = start == EigenStart::Warm, keep = start != EigenStart::Cold;
6836 if (!warm)
6837 eigSeedRhs(l0, srhs, seed);
6838 const double nrMax = eigSeed(l0, v, warm ? eigVmax_ : srhs);
6839 if (symVcycle_ && !warm) {
6840 // A cold estimate on the symmetric V-cycle ((c), DECISIONS_GPU.log 2026-10-30 "A3
6841 // finish"): lambda_max is the top Ritz value of a short PCG run from the seed, v leaves as
6842 // the top Ritz vector (the warm estimates' seed). The power iteration's 15 steps left the
6843 // top 9 % under (collocated_stability_guard: 0.995 of 1.088).
6844 lmax = lanczosTop(l0, v, keep);
6845 } else
6846 lmax = eigPowerMax(l0, v, w, z, iters);
6847 if (keep)
6848 eigKeep(eigVmax_, v, "ev_vmax", n);
6849 // The min iteration runs on shift*I - T. A shift below the true lambda_max makes it converge
6850 // to the wrong end of the spectrum and the lower bound collapse (pressure_wallbounded case B
6851 // diverged on it, doc/mg_depth_policy_log.md 2026-10-29). The power iteration approaches the
6852 // top from below and the symmetric V-cycle's top lies above 1, so in symmetric mode the shift
6853 // is raised by kChebSymShift; lambda_max itself is returned raw (Chebyshev converges for every
6854 // eigenvalue in (0, lmin + lmax), an unbracketed top costs little).
6855 double shift = symVcycle_ ? kChebSymShift * lmax : lmax;
6856 if (bracket > 1.0) {
6857 lmax *= bracket;
6858 if (shift < lmax)
6859 shift = lmax;
6860 }
6861 const double nrMin = eigSeed(l0, v, warm ? eigVmin_ : srhs);
6862 const double mu = eigPowerMin(l0, v, w, z, iters, shift);
6863 if (keep) {
6864 eigKeep(eigVmin_, v, "ev_vmin", n);
6865 // Only a non-degenerate estimate may seed a warm one: a zero seed (a zero right-hand side,
6866 // e.g. a fluid at rest) leaves zero iterates and lmax = 0, from which a warm estimate would
6867 // return zero bounds -- and a Chebyshev solve on them NaN, which maxabs cannot see.
6868 eigWarm_ =
6869 nrMax > 0.0 && nrMin > 0.0 && std::isfinite(lmax) && lmax > 0.0 && std::isfinite(mu);
6870 }
6871 eigBracket(shift, mu, lmin, lmax);
6872 }
6873 // Test hook: the NEXT estimateEigenvalues returns both bounds multiplied by `s` (s < 1 forces a
6874 // lambda_max below the spectrum's top, the growth guard's trigger). One-shot.
6875 void debugSetEigenScale(double s) { dbgEigScale_ = s; }
6876
6877 // Chebyshev semi-iteration preconditioned by ONE symmetric V-cycle -- same goal as solvePCG but
6878 // the step coefficients come from the spectral bounds [a,b], so NO per-iteration global
6879 // dot-products (communication- light at scale). rhs on level-0 supplied as `b`; solution left in
6880 // `x`. Returns the V-cycle count. Port of solve_chebyshev.
6881 // `guard3` (D3, §5.13, for a solve on warm-started bounds): if the residual after 3 iterations
6882 // is not <= r0 the solve stops there and chebyshevGuardTripped() reports it, so the caller can
6883 // re-estimate cold and redo the solve. Off, the loop is the pre-D3 loop.
6884 // `guardGrowth` (for a solve on cold-estimated bounds, doc/mg_depth_policy_log.md 2026-10-30):
6885 // if the preconditioned residual norm rho_k = r_k . z_k (z_k = M^{-1} r_k) of an iteration is
6886 // not <= rho_0 the solve stops and chebyshevGuardTripped() reports it, and the caller
6887 // re-estimates with the bracketing margin kChebBracket and redoes the solve. The norm is the
6888 // M^{-1} one: T = M^{-1} A is A-self-adjoint and the Chebyshev residual polynomial p_k(T)
6889 // satisfies |p_k| <= 1 on (0, a + b], so with bounds that bracket the spectrum rho_k <= rho_0
6890 // at every k and only a top above a + b can make it grow. The max norm has no such bound (it
6891 // rose x5.7 at iteration 1 on valid bounds, doc/mg_depth_policy_log.md 2026-10-30). rho_k is
6892 // reduced into a device slot right after the V-cycle that forms z_k and read back, one
6893 // iteration later, with the stop test's max|r| (one fence, one Allreduce of the pair), so the
6894 // guard adds no synchronisation. A comparison only: a solve that does not trip is unchanged
6895 // bit for bit.
6896 int solveChebyshev(CCField b, CCField x, int maxit, double rtol, int pre, int post, int bottom,
6897 double a, double bnd, bool guard3 = false, bool guardGrowth = false) {
6898 solveFailed_ = false; // ISSUES sweep item 6: per-solve breakdown flag
6899 chebGuardTripped_ = false;
6900 pre_ = pre;
6901 post_ = post;
6902 bottom_ = bottom;
6903 Level& l0 = lv_[0];
6904 const std::size_t n = l0.n;
6905 if (a > bnd) {
6906 double t = a;
6907 a = bnd;
6908 bnd = t;
6909 } // robust to swapped bounds
6910 a *= 0.95;
6911 bnd *= 1.05; // safety margin: [a,b] must bracket the spectrum
6912 CCField r = workVector(4, n, "cb_r"), z = workVector(5, n, "cb_z"),
6913 d = workVector(6, n, "cb_d"), w = workVector(7, n, "cb_w");
6914 auto matvec = [&](CCField y, CCField v) { matvecOverlap(l0, y, v); };
6915 auto precond = [&](CCField zz, CCField rr) { precondVcycle(zz, rr); }; // A5
6916 const double theta = 0.5 * (bnd + a), delta = 0.5 * (bnd - a), sigma1 = theta / delta;
6917 double rho = 1.0 / sigma1;
6918 matvec(w, x); // r = b - A x
6919 Kokkos::deep_copy(CCExec(), r, b);
6920 axpy(r, -1.0, w);
6921 removeMean(l0, r);
6922 const double r0 = maxabs(l0, r);
6923 // The stop reference: r0 (the default), or the caller's FULL right-hand-side norm when a
6924 // stop reference is set (setStopReference; only the balanced-force projection sets it).
6925 // With it unset rref IS r0, so `rtol * rref` is bit-for-bit the old test.
6926 const double rref = stopRef_ > 0.0 ? stopRef_ : r0;
6927 int nvc = 0;
6928 double rnLast = r0; // final |r|inf, for the trace below only
6929 // Growth guard: launch rho = r . z of the iteration just preconditioned (local partial into a
6930 // device slot, copied to pinned host memory, both asynchronous on the solve's instance).
6931 double rho0 = 0.0;
6932 auto launchRz = [&]() {
6933 ensureScalars();
6934 dotTo(l0, r, z, kChebRz);
6935 Kokkos::deep_copy(CCExec(), kcz_, slot(kChebRz));
6936 };
6937 if (r0 > 0.0) {
6938 precond(z, r);
6939 ++nvc; // z = M^{-1} r
6940 if (guardGrowth)
6941 launchRz();
6942 lin(d, 1.0 / theta, z, 0.0, z);
6943 axpy(x, 1.0, d); // d = z/theta; x += d
6944 for (int i = 1; i < maxit; ++i) {
6945 matvec(w, d);
6946 axpy(r, -1.0, w);
6947 removeMean(l0, r); // r -= A d
6948 double rhoPrev = 0.0; // guardGrowth: rho of iteration i - 1, read with max|r|
6949 const double rn = guardGrowth ? maxabsWithLocalSum(l0, r, kcz_, rhoPrev) : maxabs(l0, r);
6950 rnLast = rn;
6951 if (rn < rtol * rref)
6952 break;
6953 if (guardGrowth) {
6954 if (i == 1)
6955 rho0 = rhoPrev;
6956 else if (!(rhoPrev <= rho0)) { // the M^{-1}-norm grew: lambda_max underestimated
6957 chebGuardTripped_ = true;
6958 break;
6959 }
6960 }
6961 if (guard3 && i == 3 && !(rn <= r0)) { // growing after 3 iterations: bounds gone stale
6962 chebGuardTripped_ = true;
6963 break;
6964 }
6965 precond(z, r);
6966 ++nvc;
6967 if (guardGrowth)
6968 launchRz();
6969 const double rho_new = 1.0 / (2.0 * sigma1 - rho);
6970 lin(d, rho_new * rho, d, 2.0 * rho_new / delta, z);
6971 axpy(x, 1.0, d); // d update; x += d
6972 rho = rho_new;
6973 }
6974 }
6975 // Env-gated stop-test trace (debug output only: PECLET_FLOW_MG_DEBUG >= 2, the first
6976 // PECLET_FLOW_MG_DEBUG_SOLVES solves, rank 0), the Chebyshev counterpart of the PCG trace: r0,
6977 // the stop reference, the final |r|inf the stop test saw and the V-cycle count. It prints
6978 // values the solve already computed (no extra reduction), so the solve is unchanged with it on
6979 // or off.
6980 if (mgDebugLevel() >= 2 && dbgSolve_ < mgDebugSolves()) {
6981 if (commRank() == 0)
6982 printf(
6983 "[mg] cheb solve %d: r0=%.6e rref=%.6e rtol=%.1e |r|inf=%.6e r/rref=%.4e vcycles=%d "
6984 "maxit=%d guard=%d\n",
6985 dbgSolve_, r0, rref, rtol, rnLast, rref > 0.0 ? rnLast / rref : 0.0, nvc, maxit,
6986 chebGuardTripped_ ? 1 : 0);
6987 }
6988 ++dbgSolve_;
6989 removeMean(l0, x);
6990 return nvc;
6991 }
6992 // --- stop reference for a solve relative to the FULL right-hand side (the balanced-force
6993 // projection, flow doc/collocated_varrho_forces.md §4.6 / WO-P5). ref <= 0 restores the
6994 // default (stop relative to the initial residual). Callers set it around ONE solve only.
6995 void setStopReference(double ref) { stopRef_ = ref; }
6996 // H-2c (§8): the caller guarantees the initial iterate of the next single-rank PCG solves is
6997 // +0 everywhere (projectSolve's cold path), so the solve skips A x0. Set around ONE solve.
6998 void setZeroInitialGuess(bool on) { zeroGuess_ = on; }
6999 // E (doc/vof_projection_cost_design.md §5.3; distributed since
7000 // doc/vof_projection_distributed_design.md §6): the caller (projectSolve, PCG or FCG, any np)
7001 // asks the NEXT solve to start from the A-norm projection of its solution onto
7002 // span{v1} (hist 1) or span{v1, x} (hist 2; the solve's x holds phi^{n-1} and is overwritten
7003 // by the guess), and to stop relative to the zero-guess residual max|P b|. hist 0 = none (the
7004 // cold solve, untouched). Set around ONE solve; clearProjectedGuess() restores the default.
7005 void setProjectedGuess(CCField v1, int hist) {
7006 guessV1_ = v1;
7007 guessHist_ = hist;
7008 }
7010 guessV1_ = CCField();
7011 guessHist_ = 0;
7012 }
7013 // How many spectral-bound estimates (estimateEigenvalues) have run since construction: test
7014 // hook, it tells a re-estimate from kept bounds.
7015 long numEigenEstimates() const { return eigenEstimates_; }
7016 // Did the last solveChebyshev stop on a guard (guard3's 3-iteration test, or guardGrowth)?
7017 bool chebyshevGuardTripped() const { return chebGuardTripped_; }
7018 // max|b| over the fluid cells after the null-space (mean) projection -- the drivers' norm.
7019 double rhsNorm(CCField b, CCField scratch) {
7020 Level& l0 = lv_[0];
7021 Kokkos::deep_copy(scratch, b);
7022 removeMean(l0, scratch);
7023 return maxabs(l0, scratch);
7024 }
7025 // max|b - A x| in the same norm, computed exactly as the drivers compute their r0.
7027 Level& l0 = lv_[0];
7028 matvecOverlap(l0, Ap, x);
7029 Kokkos::deep_copy(r, b);
7030 axpy(r, -1.0, Ap);
7031 removeMean(l0, r);
7032 return maxabs(l0, r);
7033 }
7034 // Q18: the TRUE residual of the last PCG/FCG solve relative to its stop test,
7035 // max|P(b - A x)| / (rtol * rref) -- the stop test's own norm, mean removal and scale (rref is
7036 // r0 or the caller's stop reference), with the same fine operator the driver applied (the star
7037 // overlay included). < 1 means the exit really meets the tolerance; the recurrence residual the
7038 // driver tests drifts from it when the V-cycle preconditioner is indefinite (high density
7039 // contrast), and the driver can stop "converged" on a field that is not a projection. Reads x,
7040 // writes only the scratch r and Ap: one matvec and the r0 reductions, collective under MPI
7041 // (every rank gets the same value). 0 when the last solve had a zero right-hand side.
7043 const StarOverlay* star = nullptr, int nStar = 0, C3 nnStar = C3{0, 0, 0}) {
7044 if (!(cgStopRef_ > 0.0) || !(cgStopRtol_ > 0.0))
7045 return 0.0;
7046 Level& l0 = lv_[0];
7047 OverlayScope overlay(overlaySolve_, star != nullptr);
7048 matvecOverlap(l0, Ap, x);
7049 if (star)
7050 starApplyDelta(Ap, CCConst(x), *star, nStar, nnStar, l0.ext, G, l0.ext, G, exactResidual_);
7051 Kokkos::deep_copy(CCExec(), r, b);
7052 axpy(r, -1.0, Ap);
7053 removeMean(l0, r);
7054 return maxabs(l0, r) / (cgStopRtol_ * cgStopRef_);
7055 }
7056 // reductions / mean removal over inner FLUID cells (AC>tiny) of a level.
7057 double dot(Level& lv, CCField a, CCField b) {
7058 CCExec space;
7059 C3 e = lv.ext;
7060 const int g = lv.g;
7061 CCField aa = a, bb = b;
7062 FPV ac = lv.AC;
7063 double s = 0;
7064 if (hostAllFluid(lv)) // H-1: no AC read
7066 "mgdot", C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g},
7067 KOKKOS_LAMBDA(int x, int y, int z, double& acc) {
7068 const long i = (long)x + (long)y * e.x + (long)z * (long)e.x * e.y;
7069 acc += aa(i) * bb(i);
7070 },
7071 s);
7072 else
7074 "mgdot", C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g},
7075 KOKKOS_LAMBDA(int x, int y, int z, double& acc) {
7076 const long i = (long)x + (long)y * e.x + (long)z * (long)e.x * e.y;
7077 if (ac(i) > 1e-30f)
7078 acc += aa(i) * bb(i);
7079 },
7080 s);
7081#ifdef PECLET_FLOW_MPI
7082 return allreduce(s, MPI_SUM_, lv.comm);
7083#else
7084 return allreduce(s, MPI_SUM_);
7085#endif
7086 }
7087 // a . b -> ab and a . c -> ac over the inner FLUID cells in ONE lane pass and ONE allreduce of
7088 // the pair (the sum order of each is dot's).
7089 void dotPair(Level& lv, CCField a, CCField b, CCField c, double& ab, double& ac) {
7090 C3 e = lv.ext;
7091 const int g = lv.g;
7092 CCField aa = a, bb = b, cc = c;
7093 FPV fl = lv.AC;
7094 const bool all = hostAllFluid(lv); // H-1: no AC read
7095 ab = 0.0;
7096 ac = 0.0;
7098 "mgdot2", C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g},
7099 KOKKOS_LAMBDA(int x, int y, int z, double& sb, double& sc) {
7100 const long i = (long)x + (long)y * e.x + (long)z * (long)e.x * e.y;
7101 if (all || fl(i) > 1e-30f) {
7102 sb += aa(i) * bb(i);
7103 sc += aa(i) * cc(i);
7104 }
7105 },
7106 ab, ac);
7107 allreduceSum2(ab, ac
7108#ifdef PECLET_FLOW_MPI
7109 ,
7110 lv.comm
7111#endif
7112 );
7113 }
7114 double maxabs(Level& lv, CCField a) {
7115#ifdef PECLET_FLOW_MPI
7116 return allreduce(maxabsLocal(lv, a), MPI_MAX_, lv.comm);
7117#else
7118 return allreduce(maxabsLocal(lv, a), MPI_MAX_);
7119#endif
7120 }
7121 // maxabs, plus the global sum of a local partial `part` that an earlier kernel on the same
7122 // instance left in pinned host memory: the max's reduction fences the instance (so `part` is
7123 // complete), and ONE Allreduce carries {max, sum} (maxabs' MAX on the first, a SUM on the
7124 // second). The returned max is bitwise maxabs'.
7125 double maxabsWithLocalSum(Level& lv, CCField a, Kokkos::View<double, PinnedHost> part,
7126 double& sum) {
7127 const double m = maxabsLocal(lv, a);
7128 sum = part();
7129#ifdef PECLET_FLOW_MPI
7130 if (distributed_) {
7131 const auto t0 = std::chrono::steady_clock::now();
7132 double v[2] = {m, sum}, g[2] = {0.0, 0.0};
7133 MPI_Allreduce(v, g, 2, MPI_DOUBLE, maxSumOp(), lv.comm);
7134 allreduceTime_ +=
7135 std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
7136 ++allreduceCount_;
7137 sum = g[1];
7138 return g[0];
7139 }
7140#endif
7141 return m;
7142 }
7143#ifdef PECLET_FLOW_MPI
7144 // The {max, sum} pair operator of maxabsWithLocalSum (elementwise on pairs; commutative).
7145 static MPI_Op maxSumOp() {
7146 static MPI_Op op = [] {
7147 MPI_Op o;
7148 MPI_Op_create(
7149 [](void* in, void* inout, int* len, MPI_Datatype*) {
7150 const double* a = static_cast<const double*>(in);
7151 double* b = static_cast<double*>(inout);
7152 for (int k = 0; k + 1 < *len; k += 2) {
7153 b[k] = a[k] > b[k] ? a[k] : b[k];
7154 b[k + 1] += a[k + 1];
7155 }
7156 },
7157 1, &o);
7158 return o;
7159 }();
7160 return op;
7161 }
7162#endif
7163 // The rank-local max|a| over the inner FLUID cells (maxabs before its Allreduce).
7164 double maxabsLocal(Level& lv, CCField a) {
7165 CCExec space;
7166 C3 e = lv.ext;
7167 const int g = lv.g;
7168 CCField aa = a;
7169 FPV ac = lv.AC;
7170 double m = 0;
7171 if (hostAllFluid(lv)) // H-1: no AC read
7172 ccReduce3(
7173 "mgmax", C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g},
7174 KOKKOS_LAMBDA(int x, int y, int z, double& acc) {
7175 const long i = (long)x + (long)y * e.x + (long)z * (long)e.x * e.y;
7176 const double v = Kokkos::fabs(aa(i));
7177 if (v > acc)
7178 acc = v;
7179 },
7180 Kokkos::Max<double>(m));
7181 else
7182 ccReduce3(
7183 "mgmax", C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g},
7184 KOKKOS_LAMBDA(int x, int y, int z, double& acc) {
7185 const long i = (long)x + (long)y * e.x + (long)z * (long)e.x * e.y;
7186 if (ac(i) > 1e-30f) {
7187 const double v = Kokkos::fabs(aa(i));
7188 if (v > acc)
7189 acc = v;
7190 }
7191 },
7192 Kokkos::Max<double>(m));
7193 return m;
7194 }
7195 // H-1 (§8, host single rank): removeMean with the level's precomputed fluid count -- the sum
7196 // reduces in the same 4-lane pencil order (C0) as the {sum, count} pair, and an all-fluid level
7197 // reads no AC. Same cells, same order, same mean: bitwise to the single-rank path below.
7198 void removeMeanHostCounted(Level& lv, CCField f, bool stopGuard) {
7199 meanSumHostCounted(lv, f);
7200 meanSubtractHostCounted(lv, f, stopGuard);
7201 }
7202 // The sum half of removeMeanHostCounted: the fluid sum of f into kMsum (4-lane order).
7204 C3 e = lv.ext;
7205 const int g = lv.g;
7206 CCField ff = f;
7207 FPV ac = lv.AC;
7208 const bool all = lv.allFluid;
7209 if (all)
7211 "mgmeanr", C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g},
7212 KOKKOS_LAMBDA(int x, int y, int z, double& s) {
7213 s += ff((long)x + (long)y * e.x + (long)z * (long)e.x * e.y);
7214 },
7215 Kokkos::Sum<double, CCMem>(slot(kMsum)));
7216 else
7218 "mgmeanr", C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g},
7219 KOKKOS_LAMBDA(int x, int y, int z, double& s) {
7220 const long i = (long)x + (long)y * e.x + (long)z * (long)e.x * e.y;
7221 if (ac(i) > 1e-30f)
7222 s += ff(i);
7223 },
7224 Kokkos::Sum<double, CCMem>(slot(kMsum)));
7225 }
7226 // The subtract half of removeMeanHostCounted: f -= kMsum / nFluid on the fluid cells (skipped
7227 // with `stopGuard` once the PCG stop flag is set).
7228 void meanSubtractHostCounted(Level& lv, CCField f, bool stopGuard) {
7229 C3 e = lv.ext;
7230 const int g = lv.g;
7231 CCField ff = f;
7232 FPV ac = lv.AC;
7233 const bool all = lv.allFluid;
7234 auto ks = ks_;
7235 const long cnt = lv.nFluid;
7236 const bool guard = stopGuard;
7237 ccFor3(
7238 "mgmeans", C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g}, KOKKOS_LAMBDA(int x, int y, int z) {
7239 if (cnt == 0 || (guard && ks(kStop) != 0.0))
7240 return;
7241 const double mean = ks(kMsum) / (double)cnt;
7242 const long i = (long)x + (long)y * e.x + (long)z * (long)e.x * e.y;
7243 if (all)
7244 ff(i) -= mean;
7245 else
7246 meanSubtractCell(ff, ac, i, mean);
7247 });
7248 }
7249 // C4 (§6 amendment 2): the level-0 V-cycle exit removeMean of z = lv.x (removeMeanHostCounted:
7250 // the sum, then the subtract) with r^T z (r = lv.rhs) accumulated in the subtract pass, with
7251 // dotTo's mask, operand order and 4-lane order -- bitwise to removeMean(lv, z) + dotTo(lv, r,
7252 // z, k). With `p` allocated also p = z (copyDotTo's H-2b fusion, under its own condition).
7253 void removeMeanDotTo(Level& lv, int k, CCField p) {
7254 meanSumHostCounted(lv, lv.x);
7255 const C3 e = lv.ext;
7256 const int g = lv.g;
7257 CCField zz = lv.x, rr = lv.rhs, pp = p;
7258 FPV ac = lv.AC;
7259 const bool all = lv.allFluid, copyP = p.extent(0) != 0;
7260 const long cnt = lv.nFluid;
7261 auto ks = ks_;
7263 "mgmeans_dot", C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g},
7264 KOKKOS_LAMBDA(int x, int y, int zc, double& acc) {
7265 const long i = (long)x + (long)y * e.x + (long)zc * (long)e.x * e.y;
7266 if (cnt != 0) {
7267 const double mean = ks(kMsum) / (double)cnt;
7268 if (all)
7269 zz(i) -= mean;
7270 else
7271 meanSubtractCell(zz, ac, i, mean);
7272 }
7273 if (copyP)
7274 pp(i) = zz(i);
7275 if (all || ac(i) > 1e-30f)
7276 acc += rr(i) * zz(i);
7277 },
7278 slot(k));
7279 }
7280 // Single rank (A6, §5.6): the {sum, count} reduce into device slots with the same policy and
7281 // functor, and the subtract kernel forms mean = sum / count itself -- no host read. With
7282 // `stopGuard` the subtract is skipped once the PCG stop flag is set (solvePCGResident keeps r
7283 // exactly as the host-scalar loop leaves it at a break). Distributed: the Allreduce path below.
7284 void removeMean(Level& lv, CCField f, bool stopGuard = false) {
7285 if (!removeMean_)
7286 return; // non-singular operator (Dirichlet outflow present) -> no null-space projection
7287 CCExec space;
7288 C3 e = lv.ext;
7289 const int g = lv.g;
7290 CCField ff = f;
7291 FPV ac = lv.AC;
7292 // the {sum, count} body; ccReduce3Lanes runs it in the 4-lane pencil order on a host backend
7293 // (WO-C0, doc/vof_projection_cost_design.md §6) and as the MDRange reduction it always was on a
7294 // device
7295 auto body = KOKKOS_LAMBDA(int x, int y, int z, double& s, long& k) {
7296 const long i = (long)x + (long)y * e.x + (long)z * (long)e.x * e.y;
7297 if (ac(i) > 1e-30f) {
7298 s += ff(i);
7299 k += 1;
7300 }
7301 };
7302 if (!distributed_) {
7303 ensureScalars();
7304 if (kHostMemory && lv.nFluid >= 0) { // H-1: the precomputed count, no count reduction
7305 removeMeanHostCounted(lv, f, stopGuard);
7306 return;
7307 }
7308 // S1 (doc/vof_gpu_coarse_tail_design.md §5.1): on a device the count was counted at the
7309 // operator build -- a single-result (asynchronous) sum; the {sum, count} pair otherwise
7310 assert(kHostMemory || lv.nFluidDevValid); // a deferred level is never mean-projected
7311 const bool devCounted = !kHostMemory && lv.nFluidDevValid;
7312 if (devCounted)
7314 "mgmeanr", C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g},
7315 KOKKOS_LAMBDA(int x, int y, int z, double& s) {
7316 const long i = (long)x + (long)y * e.x + (long)z * (long)e.x * e.y;
7317 if (ac(i) > 1e-30f)
7318 s += ff(i);
7319 },
7320 Kokkos::Sum<double, CCMem>(slot(kMsum)));
7321 else
7322 ccReduce3Lanes("mgmeanr", C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g}, body,
7323 Kokkos::Sum<double, CCMem>(slot(kMsum)), Kokkos::Sum<long, CCMem>(kcnt_));
7324 auto ks = ks_;
7325 auto kc = devCounted ? lv.nFluidDev : kcnt_;
7326 const bool guard = stopGuard;
7327 ccFor3(
7328 "mgmeans", C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g},
7329 KOKKOS_LAMBDA(int x, int y, int z) {
7330 const long cnt = kc();
7331 if (cnt == 0 || (guard && ks(kStop) != 0.0))
7332 return;
7333 const double mean = ks(kMsum) / (double)cnt;
7334 const long i = (long)x + (long)y * e.x + (long)z * (long)e.x * e.y;
7335 meanSubtractCell(ff, ac, i, mean);
7336 });
7337 return;
7338 }
7339 double sum = 0;
7340 long cnt = 0;
7341 ccReduce3Lanes("mgmeanr", C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g}, body, sum, cnt);
7342 double mean = 0.0;
7343 if (!globalMean(lv, sum, cnt, mean))
7344 return;
7345 ccFor3(
7346 "mgmeans", C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g}, KOKKOS_LAMBDA(int x, int y, int z) {
7347 const long i = (long)x + (long)y * e.x + (long)z * (long)e.x * e.y;
7348 meanSubtractCell(ff, ac, i, mean);
7349 });
7350 }
7351 // The distributed removeMean's global mean: the local fluid {sum, count} summed over the
7352 // level's ranks by ONE allreduceSum2 (one latency hit for the pair). false when the global
7353 // count is 0 (removeMean then subtracts nothing).
7354 bool globalMean(Level& lv, double sum, long cnt, double& mean) {
7355 double dcnt = (double)cnt;
7356 allreduceSum2(sum, dcnt
7357#ifdef PECLET_FLOW_MPI
7358 ,
7359 lv.comm
7360#endif
7361 );
7362 cnt = (long)dcnt;
7363 if (cnt == 0)
7364 return false;
7365 mean = sum / (double)cnt;
7366 return true;
7367 }
7368
7369 // --- K4 (doc/vof_distributed_host_comm_design.md §5.4): distributed host Krylov fusion ------
7370 // C2-C4 of doc/vof_projection_cost_design.md §6 in the distributed host-scalar loops of
7371 // solvePCGAttempt and solveFCGAttempt: the same cells, operand order, masks and 4-lane order
7372 // as the unfused kernels, then the SAME MPI calls in the same order (removeMean's
7373 // allreduceSum2, maxabs' MAX, dot's SUM), so every global scalar is bitwise unchanged at every
7374 // np. Host memory and a singular operator only (removeMean_: otherwise removeMean spends no
7375 // Allreduce and there is no sum to fuse); C1 is not ported (the box matvec splits rows between
7376 // interior and shell, so the lane order cannot be kept). Elsewhere the unfused kernels.
7377 bool distKrylovFusion() const { return kHostMemory && distributed_ && removeMean_; }
7378 // C2 + C3: x += alpha p, r -= alpha Ap (axpy's expressions) over the INNER cells, with the
7379 // fluid {sum, count} of the new r in removeMean's body and 4-lane order; the global mean
7380 // (removeMean's allreduceSum2); then the subtract (meanSubtractCell, skipped on a zero global
7381 // count) fused with the local max|r| (maxabs' predicate and Max reducer; max is order-free) and
7382 // maxabs' MAX Allreduce. Returns the global max|r|: bitwise to axpy, axpy, removeMean, maxabs.
7383 // The ghost entries of x and r are no longer updated (§ C amendment 4): no reader consumes them
7384 // -- the matvec exchanges or wrap-reads p, never x or r; the V-cycle reads r = l0.rhs at inner
7385 // cells only (no level-0 rhs exchange: A5), the FP32 entry/exit likewise; the reductions and
7386 // the final removeMean run over inner cells; the caller copies x's inner cells (copyInner), and
7387 // a warm-start / projected-guess x is exchanged or wrap-read by the next solve's matvec.
7389 double alpha) {
7390 const C3 e = l0.ext;
7391 const int g = l0.g;
7392 CCField xx = x, rr = r, pp = p, aa = Ap;
7393 FPV ac = l0.AC;
7394 const double a = alpha, na = -alpha;
7395 double sum = 0;
7396 long cnt = 0;
7398 "mgpcg_update_sum", C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g},
7399 KOKKOS_LAMBDA(int x_, int y, int z, double& s, long& k) {
7400 const long i = (long)x_ + (long)y * e.x + (long)z * (long)e.x * e.y;
7401 xx(i) += a * pp(i);
7402 rr(i) += na * aa(i);
7403 if (ac(i) > 1e-30f) {
7404 s += rr(i);
7405 k += 1;
7406 }
7407 },
7408 sum, cnt);
7409 double mean = 0.0;
7410 const bool sub = globalMean(l0, sum, cnt, mean);
7411 double m = 0;
7412 ccReduce3(
7413 "mgmeans_max", C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g},
7414 KOKKOS_LAMBDA(int x_, int y, int z, double& acc) {
7415 const long i = (long)x_ + (long)y * e.x + (long)z * (long)e.x * e.y;
7416 if (sub)
7417 meanSubtractCell(rr, ac, i, mean);
7418 if (ac(i) > 1e-30f) {
7419 const double v = Kokkos::fabs(rr(i));
7420 if (v > acc)
7421 acc = v;
7422 }
7423 },
7424 Kokkos::Max<double>(m));
7425#ifdef PECLET_FLOW_MPI
7426 return allreduce(m, MPI_MAX_, l0.comm);
7427#else
7428 return allreduce(m, MPI_MAX_);
7429#endif
7430 }
7431 // C4, the level-0 V-cycle exit (vcycleImpl, on request of precondDotDist): removeMean(lv, z =
7432 // lv.x)'s distributed {sum, count} reduce and allreduceSum2, then the subtract fused with the
7433 // local r^T z (r = lv.rhs: A5 binds the caller's r) in dot's mask, operand order and 4-lane
7434 // order. Returns the LOCAL r^T z; the caller spends dot's SUM Allreduce on it.
7436 const C3 e = lv.ext;
7437 const int g = lv.g;
7438 CCField zz = lv.x, rr = lv.rhs;
7439 FPV ac = lv.AC;
7440 double sum = 0;
7441 long cnt = 0;
7443 "mgmeanr", C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g},
7444 KOKKOS_LAMBDA(int x, int y, int z, double& s, long& k) {
7445 const long i = (long)x + (long)y * e.x + (long)z * (long)e.x * e.y;
7446 if (ac(i) > 1e-30f) {
7447 s += zz(i);
7448 k += 1;
7449 }
7450 },
7451 sum, cnt);
7452 double mean = 0.0;
7453 const bool sub = globalMean(lv, sum, cnt, mean);
7454 double acc = 0;
7456 "mgmeans_dot", C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g},
7457 KOKKOS_LAMBDA(int x, int y, int zc, double& d) {
7458 const long i = (long)x + (long)y * e.x + (long)zc * (long)e.x * e.y;
7459 if (sub)
7460 meanSubtractCell(zz, ac, i, mean);
7461 if (ac(i) > 1e-30f)
7462 d += rr(i) * zz(i);
7463 },
7464 acc);
7465 return acc;
7466 }
7467 // C4's driver half: z = M r (precondVcycle) with r^T z formed in the level-0 exit pass, then
7468 // dot's SUM Allreduce; a V-cycle without that exit (a one-level hierarchy) leaves `done` false
7469 // -> dot(). Returns the global r^T z: bitwise to precondVcycle(z, r) + dot(l0, r, z).
7471 bool on = false, done = false;
7472 double local = 0.0;
7473 };
7476 struct Reset { // the request never outlives this V-cycle (exception-safe)
7477 ExitDotDist& d;
7478 ~Reset() { d = ExitDotDist{}; }
7479 } reset{exitDotDist_};
7480 exitDotDist_ = ExitDotDist{true, false, 0.0};
7481 precondVcycle(z, r);
7482 Level& l0 = lv_[0];
7483 if (!exitDotDist_.done)
7484 return dot(l0, r, z);
7485#ifdef PECLET_FLOW_MPI
7486 return allreduce(exitDotDist_.local, MPI_SUM_, l0.comm);
7487#else
7488 return allreduce(exitDotDist_.local, MPI_SUM_);
7489#endif
7490 }
7491
7492 // Mean-removal scope. "all" (legacy): project the nullspace out at every V-cycle level,
7493 // after every matvec and on every residual update — ~10 extra MPI_Allreduce latency hits per
7494 // Krylov iteration whose only role is FP hygiene. "fine" (DEFAULT) keeps the removals that carry
7495 // the algorithm (the rhs/residual projections + the fine-level V-cycle exit + the final iterate)
7496 // and drops the interior-level ones: A maps mean-free vectors to mean-free vectors, so the Krylov
7497 // space never sees the dropped components (they lie in the nullspace and are removed from the
7498 // final x). Validated by iteration-count parity; not bit-identical to "all".
7499 void setMeanRemovalScope(bool all) {
7500 const bool carry = fp32Carriable(), defer = fp64Deferrable();
7501 meanRemovalAll_ = all;
7502 fp32Reconfigure(carry, defer); // D: the scope is an eligibility condition (§4.2 P8)
7503 }
7504
7505 // Accumulated wall time / call count of the global reductions (every dot product, residual max
7506 // and mean-removal funnels through allreduce()). This is THE latency-bound term of the
7507 // distributed pressure solve; the solver resets it per step and exposes it to Python.
7508 double allreduceSeconds() const { return allreduceTime_; }
7509 long allreduceCount() const { return allreduceCount_; }
7510 // ISSUES sweep item 6: did the LAST solve driver give up on a non-finite recurrence scalar?
7511 // A failing solve returns the ITERATION CAP (so a rule-3b "no capped solve" check sees it) and
7512 // sets this; it used to print to stdout, zero the correction and report 0 iterations.
7513 // The device bottom flags a non-finite scalar on the device; a driver whose host reads do not
7514 // carry it (all but the single-rank PCG packet) has it folded in here, by one scalar read.
7516 if (bottomFlagPending_)
7518 return solveFailed_;
7519 }
7521 allreduceTime_ = 0.0;
7522 allreduceCount_ = 0;
7523 }
7524
7525 private:
7526 enum AllOp { kSum, kMax };
7527#ifdef PECLET_FLOW_MPI
7528 using MPI_Comm_or_void = MPI_Comm;
7529 static MPI_Comm nullptr_comm() { return MPI_COMM_NULL; }
7530#else
7531 using MPI_Comm_or_void = void*;
7532 static void* nullptr_comm() { return nullptr; }
7533#endif
7534 // Global reduction over ranks (no-op single-rank / non-distributed -> byte-identical to the local
7535 // reduce).
7536 double allreduce(double v, AllOp op, MPI_Comm_or_void c = nullptr_comm()) {
7537#ifdef PECLET_FLOW_MPI
7538 if (distributed_) {
7539 const auto t0 = std::chrono::steady_clock::now();
7540 double g = 0;
7541 MPI_Allreduce(&v, &g, 1, MPI_DOUBLE, op == kSum ? MPI_SUM : MPI_MAX,
7542 c == nullptr_comm() ? comm_ : c);
7543 allreduceTime_ +=
7544 std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
7545 ++allreduceCount_;
7546 return g;
7547 }
7548#endif
7549 (void)op;
7550 return v;
7551 }
7552 // One MPI_Allreduce of a {sum, count} pair — elementwise MPI_SUM on a 2-vector is bit-identical
7553 // to two separate allreduces, at half the latency hits.
7554 void allreduceSum2(double& a, double& b, MPI_Comm_or_void c = nullptr_comm()) {
7555#ifdef PECLET_FLOW_MPI
7556 if (distributed_) {
7557 const auto t0 = std::chrono::steady_clock::now();
7558 double v[2] = {a, b}, g[2] = {0.0, 0.0};
7559 MPI_Allreduce(v, g, 2, MPI_DOUBLE, MPI_SUM, c == nullptr_comm() ? comm_ : c);
7560 allreduceTime_ +=
7561 std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
7562 ++allreduceCount_;
7563 a = g[0];
7564 b = g[1];
7565 }
7566#endif
7567 }
7568 static constexpr AllOp MPI_SUM_ = kSum, MPI_MAX_ = kMax;
7569
7570 std::vector<Level> lv_;
7571 CCField work_[8]; // workVector's slots (0-3 the eigenvalue estimate, 4-7 the Chebyshev driver)
7572 // D3 (§5.13): the last v_max / v_min power iterates of a ColdKeep/Warm estimate, persistent
7573 // across solves (never zeroed), valid while eigWarm_ (dropped by init/initMpi).
7574 CCField eigVmax_, eigVmin_;
7575 bool eigWarm_ = false;
7576 bool chebGuardTripped_ = false; // see chebyshevGuardTripped()
7577 // The physical metric (setMetric), doc/anisotropic_metric.md §5: h_a' = h_a/hRef and the flag
7578 // that engages the aspect-ratio coarsening rule. (1,1,1)/false is the isotropic lattice, on
7579 // which mgChooseRatio reproduces today's level table exactly.
7580 double hp_[3] = {1.0, 1.0, 1.0};
7581 bool aniso_ = false;
7582 int pre_ = 2, post_ = 2, bottom_ = 4;
7583 int bc_[6] = {0, 0, 0, 0, 0, 0};
7584 bool hasBC_ = false, removeMean_ = true, hasOutflow_ = false;
7585 // WO-R2 item 1. OFF by default and then every path is byte-identical to before it existed: the
7586 // outflow face keeps the literal 1.0 the raw-openness operator wants. The varRho pressure build
7587 // (IbmSolver::project) turns it on for its own setOpenness call, because the field it hands over
7588 // is the COEFFICIENT open_f*rho0/rho_f and the 1.0 would overwrite the boundary rows of it.
7589 bool outflowCoeff_ = false;
7590 CCField bcPlane_[3]; // level-0 high-side outflow coefficient plane, per axis (saveOutflowPlanes)
7591 // Default "fine" (measured winner of the at-scale ablation, Snellius H100 8+16 GPUs: 5.5%
7592 // faster than "all" with identical iteration counts; single-rank the reductions are free either
7593 // way). setMeanRemovalScope(true) restores the legacy every-level scope.
7594 bool meanRemovalAll_ = false;
7595 bool distributed_ = false;
7596 bool stencilHaloOff_ = false; // K3 test hook (debugSetStencilHaloOff)
7597 bool overlaySolve_ = false; // A3: the current solve has an overlay (OverlayScope)
7598 int dbgBrkWhich_ = 0, dbgBrkIter_ = -1; // setDebugBreakdown (test hook)
7599 int dbgSolve_ = 0; // solve counter for the env-gated convergence trace (mgDebugLevel() >= 2)
7600 long eigenEstimates_ = 0; // estimateEigenvalues calls since construction (numEigenEstimates)
7601 double dbgEigScale_ = 1.0; // debugSetEigenScale (test hook)
7602 int dbgBicgBreakdowns_ = 0; // solveBiCGStab breakdown exits (1-5), for its debug trace only
7603 int dbgBicgStagnations_ = 0; // solveBiCGStab compatibility-floor exits, for its debug trace only
7604 // ISSUES sweep item 6: did the LAST Krylov solve give up on a non-finite recurrence
7605 // scalar (a preconditioner or operator that produced NaN/Inf)? Reset at the head of
7606 // every solve. See `lastSolveFailed()`.
7607 bool solveFailed_ = false;
7608 // The device bottom (§5.7, §5.14, §13): the FCG vectors, the kernel's info slot, the component
7609 // labels (condition 6, cached per hierarchy), and whether a device solve ran since its flag was
7610 // last read.
7611 CCField bottomR_, bottomP_, bottomZ_, bottomZp_, bottomAp_;
7612 Kokkos::View<int*, CCMem> bottomInfo_; // [0] = inner iterations of the last device solve
7613 bool bottomConnKnown_ = false, bottomConnected_ = false; // condition 6 (B1b), per hierarchy
7614 int bottomNComp_ = 0; // the bottom's fluid components
7615 Kokkos::View<int*, CCMem> bottomComp_, bottomLabTmp_; // component ids (-1 solid), label scratch
7616 Kokkos::View<long*, CCMem> bottomCompCnt_; // cells per component
7617 CCField bottomCompMean_; // the kernel's per-component means
7618 bool bottomFlagPending_ = false; // a device solve ran since the device flag was last read
7619 int bottomSolver_ = 0; // kBottomAuto / kBottomDirect / kBottomAlgebraic
7620 // §13, the direct preconditioner: the bottom storage exists (single rank, <= 8192 cells, device
7621 // or forced by a hook), the plane ordering, the FP32 factor, the per-component augmentation, the
7622 // factor's staleness (set by setOpenness), the two kernels' team sizes, the first attempt's
7623 // pivot floor (kBottomPivotTol; the U5 hook raises it).
7624 bool bottomStore_ = false;
7625 // §14 H-6: the host global bottom (buildGlobalBottomLevel), whether it is the direct bottom's
7626 // level, this rank's inner global ids (gb_'s private map) and every bottom rank's in gather
7627 // order.
7628 Level gb_;
7629 bool gbActive_ = false;
7630 std::vector<int> gbLocal_, gbGid_;
7631 // per bottom rank (bt.comm order): inner cell counts and displacements, x1 (gids, rhs) and x3
7632 // (the interleaved openness), fixed per hierarchy.
7633 std::vector<int> gbCnt1_, gbDsp1_, gbCnt3_, gbDsp3_;
7634 // Review note 1 (directBottomIneligibleAll): the bottom's global dims (gdim; agglomerateBottom's
7635 // ratio-derived extent) and label code, agreed over comm_ once per hierarchy.
7636 bool dirAgreedKnown_ = false;
7637 int dirAgreedCode_ = 1;
7638 C3 dirAgreedGdim_{}, dirAgreedExt_{};
7639 BottomPlanes dirPlanes_;
7640 BottomDirect<float> dir_; // PRECISION-EXEMPT: the FP32 direct factor under an FP64 FCG (§13)
7641 Kokkos::View<int*, CCMem> dirKc_;
7642 Kokkos::View<double*, CCMem> dirAug_;
7643 bool facStale_ = true;
7644 int dirTeam_ = 0, dirFacTeam_ = 0;
7645 std::optional<CCExec> side_; // X: the factor's side instance (partition_space, lazily)
7646 mutable bool facPending_ = false; // X: a side factor was launched and not yet joined
7647 long prefactorLaunches_ = 0; // X: side factors launched (diagnostics)
7648 double dirPivotTol_ = kBottomPivotTol;
7649 double stopRef_ = -1.0; // see setStopReference
7650 double cgStopRef_ = 0.0, cgStopRtol_ = 0.0; // Q18: the last PCG/FCG attempt's rref and rtol
7651 bool zeroGuess_ = false; // see setZeroInitialGuess
7652 CCField guessV1_; // E: phi^n (setProjectedGuess)
7653 int guessHist_ = 0; // E: 0 none, 1 span{phi^n}, 2 span{phi^n, phi^{n-1}}
7654 double guessC1_ = 0.0, guessC2_ = 0.0; // E: the last guess's coefficients (trace)
7655 CCField guessX0_, guessTA_, guessTB_; // E trace buffers (PECLET_FLOW_MG_DEBUG >= 2 only)
7656 std::vector<double> lvTime_; // per-level V-cycle wall time (mgDebugLevel() >= 3)
7657 int lvCycles_ = 0;
7658 // Zero-gradient (Neumann) coarse ghost before the prolongation on wall/inflow faces — the WO-H
7659 // symmetry repair (see applyNeumannGhost). ON by default; `setCoarseGhost(false)` restores the
7660 // pre-2026-08-30 periodic-wrap ghost purely as a MEASUREMENT ABLATION (it reinstates the
7661 // asymmetry that stalls MG-PCG on every 3-D wall-bounded grid — never a production setting).
7662 // Inert on periodic/IBM problems (hasBC_ == false), where the fix is a no-op either way.
7663 bool bcGhost_ = true;
7664 // The aspect-ratio coarsening threshold `theta` of doc/anisotropic_metric.md §5.1
7665 // (`setAspectThreshold`; only ever consulted on an ANISOTROPIC metric). 1e9 restores full
7666 // coarsening (the §8.5 item (c) ablation), 1.4142 is the sqrt(2) variant §5.2 weighs against 2.0.
7667 double aspectTheta_ = 2.0;
7668 bool lineRelax_ =
7669 true; // A2.4: the line smoother on triggered smoothed levels (setLineRelaxation)
7670 bool symVcycle_ = true; // A3: P = c R^T + the palindromic bottom (setSymmetricVcycle)
7671 // Communication-avoiding smoothing (see the kCa* enum): kCaDefault (host both, device off). Only
7672 // kCaMg is read here; the momentum half lives in IbmSolver.
7673 int caMode_ = kCaDefault;
7674 // ISSUES sweep item 6. `setStrictPressure(true)` turns a non-finite preconditioner output into a
7675 // throw instead of a printed line + a zero correction. Off by default: the shipped behaviour is
7676 // to report the cap through `last_pressure_iterations()` and raise the `pressure_solve_failed()`
7677 // flag, so a rule-3b check catches it without changing control flow.
7678 bool strictPressure_ = false;
7679 // P1 of the defect-correction campaign — the exact (matrix-free, double, flux-form) level-0
7680 // operator apply in the residual and the Krylov matvec. See mac_cutcell.hpp.
7681 bool exactResidual_ = false;
7682 // D (§4.4.6): the V-cycle precision mode. kVcycleAuto = the default since WO-F (USER
7683 // 2026-10-19; doc/vof_projection_distributed_design.md §9): FP32 where eligible on a device
7684 // backend, single rank and distributed, FP64 restart on failure; host 'auto' = FP64.
7685 // kVcycleFp64 / kVcycleFp32 forced. opBuilt_: setOpenness has built the operator of the current
7686 // hierarchy.
7687 int vprec_ = kVcycleAuto;
7688 bool opBuilt_ = false;
7689 // Finding 5: the per-level face-range flags of the FP32 weights (device) and their read-back.
7690 Kokkos::View<int*, CCMem> wBad_;
7691 int fp32Last_ = -1; // D-dist (§5.2): computeFp32Last, whenever lv_ is built
7692 mutable Kokkos::View<int*, Kokkos::SharedHostPinnedSpace> wBadHost_; // S2: pinned
7693 mutable bool wBadStale_ = false;
7694 // D5 (§4.4.7): the non-bottom levels' FP64 V-cycle data do not hold the current operator (the
7695 // last build deferred them, or the setter released them); ensureFp64 rebuilds them.
7696 bool fp64Stale_ = false;
7697 bool lastVcycleFp32_ = false;
7698 // R (doc/vof_projection_distributed_design.md §4): the FP64 restart of a non-converged FP32
7699 // attempt under 'auto'. fp32Latched_: a restart latched 'auto' to FP64 (mode state, like vprec_:
7700 // it survives init, initMpi and geometry rebuilds; setVcyclePrecision clears it).
7701 // lastSolveConverged_: the last attempt met its stop test or started with r0 == 0.
7702 // attemptMaxit_: the iteration limit the last attempt ran with (the kind-2 fault lowers it).
7703 bool fp32Latched_ = false;
7704 bool lastSolveConverged_ = false;
7705 int attemptMaxit_ = 0;
7706 int vcycleRestarts_ = 0;
7707 int lastDiscardedIters_ = 0;
7708 // debugSetFp32Fault (test hook): kind 0 off, 1 NaN exit scale on the at-th FP32 V-cycle of an
7709 // attempt, 2 an FP32 attempt runs at most `at` iterations; fp32FaultCount_ counts the V-cycles.
7710 int fp32FaultKind_ = 0, fp32FaultAt_ = 0, fp32FaultCount_ = 0;
7711 bool healthTrace_ = false; // §4.4.5 test hook (setHealthTrace)
7712 std::vector<double> healthLog_; // the last single-rank PCG / FCG solve's health ratios
7713 // The `agglomerateBottom()` auto criterion: agglomerate once the coarsest GLOBAL grid exceeds
7714 // this many cells on any axis (`setAgglomerationExtent`).
7715 int agglomExtent_ = 4;
7716 double allreduceTime_ = 0.0;
7717 long allreduceCount_ = 0;
7718 // --- decomposition-agnostic algebraic bottom solve (GraphAMG) ---
7719 // The geometric coarse hierarchy needs a cleanly-coarsening (equal-weight) ORB. Under a WEIGHTED
7720 // decomposition the coarse levels misalign, so the multilevel path is unavailable and only pure
7721 // RB-GS (nLevels==1) works. With this enabled, the coarsest level is solved by an AGGLOMERATED
7722 // algebraic multigrid: the operator + rhs of the coarsest level are gathered to rank 0, solved by
7723 // a mesh-agnostic smoothed-aggregation AMG (core::solver::GraphAMG, exact by construction on any
7724 // decomposition), and the solution scattered back. With nLevels==1 this makes the whole pressure
7725 // solve mesh-independent AND decomposition-agnostic.
7726 int agglomMode_ = 0; // 0 smoothed bottom (default), -1 auto (see agglomerateBottom), 1 always
7727 // Coarse-level telescoping (see Telescope). DEFAULT ON since 2026-09-02 (the FoxBerry ladder);
7728 // `setTelescope(false)` restores the in-place-only hierarchy, which is byte-identical to before
7729 // telescoping existed. teleForce_ > 0 forces a telescope at that level even when in-place
7730 // coarsening is legal (tests: compare the two hierarchies on one problem).
7731 bool telescope_ = true;
7732 int teleForce_ = -1;
7733 bool teleActive_ = true; // false on a rank that idles below a telescope point
7734 // Economic trigger (MueLu's "min rows per proc", PETSc's reduction factor): once a level's
7735 // smallest block extent drops below this, merge -- and merge far enough that the merged blocks
7736 // clear it -- even if in-place coarsening is still legal. A 1x3x3 block on 1024 ranks is a
7737 // halo exchange with nine cells of work behind it. 0 disables (merge only when blocked).
7738 int teleMinExtent_ = 4;
7739 // Repartition stages (setRepartition): bound the block a telescope stage may hand a rank by the
7740 // largest level-0 block, repartitioning the level onto a proportional ORB on fewer ranks where a
7741 // sibling merge would exceed it. OFF by default (sibling merges only, byte-identical to S4); the
7742 // Solver switches it on for a weighted level-0 decomposition.
7743 bool repartition_ = false;
7744 int gnxF_ = 0, gnyF_ = 0, gnzF_ = 0; // GLOBAL fine dims (== local single-rank)
7745 // Fine-level 1/h^2 per axis, as handed to setOpenness. Only the exact (matrix-free) level-0
7746 // apply reads them; the bands carry gf already folded in.
7747 double gfx_ = 1.0, gfy_ = 1.0, gfz_ = 1.0;
7748 mutable std::shared_ptr<peclet::core::solver::GraphAMG>
7749 amg_; // built once from the bottom operator
7750 mutable peclet::core::solver::HostCsrOp
7751 amgA_; // rank 0: the assembled global bottom operator (CG matvec)
7752 mutable std::vector<int> amgOwnerCount_; // rank 0: #bottom cells each rank owns (gather layout)
7753 mutable std::vector<int>
7754 amgGlobalOfLocal_; // this rank's bottom inner cells -> global bottom index
7755 mutable int amgGlobalN_ = 0; // total bottom global cells (rank 0)
7756 // PECLET_FLOW_AGMG_DEBUG instrumentation (see agmgDebug()): per-gid solid marker + call counter.
7757 mutable std::vector<std::uint8_t> amgSolid_;
7758 mutable std::vector<int> amgComp_; // fluid component id per gid (-1 = solid identity row)
7759 mutable int amgNComp_ = 0; // number of fluid components (null-space dimension)
7760 mutable long agmgCalls_ = 0;
7761 static int agmgDebug() {
7762 static const int v = [] {
7763 const char* e = std::getenv("PECLET_FLOW_AGMG_DEBUG");
7764 return e ? std::atoi(e) : 0;
7765 }();
7766 return v;
7767 }
7768#ifdef PECLET_FLOW_MPI
7769 MPI_Comm comm_ = MPI_COMM_NULL;
7770#endif
7771
7772 public:
7773 // Enable the agglomerated GraphAMG bottom solve (decomposition-agnostic multigrid coarse solve).
7774 // Rebuilds lazily on the next solve. Safe single-rank (local assemble + serial AMG).
7775 void setAgglomerationMode(int mode) { agglomMode_ = mode; } // -1 auto, 0 never, 1 always
7776 void setAgglomerationExtent(int cells) { agglomExtent_ = cells > 0 ? cells : 4; }
7777 int agglomerationExtent() const { return agglomExtent_; }
7778 void setTelescope(bool on) { telescope_ = on; }
7780 void setCoarseGhost(bool on) { bcGhost_ = on; }
7781 bool coarseGhost() const { return bcGhost_; }
7783 void setAspectThreshold(double theta) { aspectTheta_ = theta; }
7787 void setLineRelaxation(bool on) {
7788 if (on != lineRelax_)
7789 eigWarm_ = false;
7790 lineRelax_ = on;
7791 }
7792 bool lineRelaxation() const { return lineRelax_; }
7799 void setSymmetricVcycle(bool on) {
7800 if (on != symVcycle_)
7801 eigWarm_ = false;
7802 symVcycle_ = on;
7803 }
7804 bool symmetricVcycle() const { return symVcycle_; }
7805 double aspectThreshold() const { return aspectTheta_; }
7807 void setCommAvoiding(int mask) { caMode_ = mask; }
7808 int commAvoiding() const { return caMode_; }
7810 void setStrictPressure(bool on) { strictPressure_ = on; }
7811 bool strictPressure() const { return strictPressure_; }
7813 void setExactResidual(bool on) {
7814 const bool carry = fp32Carriable(), defer = fp64Deferrable();
7815 exactResidual_ = on;
7816 fp32Reconfigure(carry, defer); // D5 (§4.4.7): the exact outer leaves level 0's AFX unread
7817 }
7818 bool exactResidual() const { return exactResidual_; }
7819 // WO-R2 item 1: the next setOpenness receives a variable-density COEFFICIENT field, so the
7820 // Dirichlet (outflow) domain-face rows must carry the caller's coefficient rather than the
7821 // literal openness 1.0. See applyBoundaryOpenness. Reset it for a raw-openness build.
7822 void setOutflowCoefficient(bool on) { outflowCoeff_ = on; }
7823 bool outflowCoefficient() const { return outflowCoeff_; }
7824 // Diagnostics for the tests / the prediction tool: telescope points this rank passed through,
7825 // and the coarsest GLOBAL grid of the hierarchy (valid on a rank that holds every level, e.g.
7826 // rank 0, which is always a group root).
7827 int telescopeCount() const {
7828 int n = 0;
7829#ifdef PECLET_FLOW_MPI
7830 for (const Level& l : lv_)
7831 n += l.tele ? 1 : 0;
7832#endif
7833 return n;
7834 }
7835 // Repartition stages this rank passed through (a subset of telescopeCount()).
7836 int repartitionCount() const {
7837 int n = 0;
7838#ifdef PECLET_FLOW_MPI
7839 for (const Level& l : lv_)
7840 n += (l.tele && l.tele->repartition()) ? 1 : 0;
7841#endif
7842 return n;
7843 }
7845 C3 g{gnxF_, gnyF_, gnzF_};
7846 for (std::size_t L = 0; L + 1 < lv_.size(); ++L)
7847 g = C3{g.x / lv_[L].ratio.x, g.y / lv_[L].ratio.y, g.z / lv_[L].ratio.z};
7848 return g;
7849 }
7850#ifdef PECLET_FLOW_MPI
7851 // The hierarchy initMpi WOULD build, as a pure function of (grid, rank count, levels, telescope,
7852 // decomposition mode) — no MPI, no allocation, so it runs on a laptop for any rank count. One row
7853 // per level: global dims, ranks holding it, block dims (block 0), ratio to the next level, and
7854 // whether the transition out of it telescopes. This is the pre-flight for a job (P1 of
7855 // docs/MG_TELESCOPING_PLAN.md) and replaces launching `np` oversubscribed processes to find out.
7856 // NOTE (Phase 2 C3): this planner models the ISOTROPIC rule -- it takes no metric, so it does
7857 // NOT apply the aspect-ratio deferral of doc/anisotropic_metric.md §5. On an anisotropic
7858 // `extent` read the real table off the built hierarchy instead
7859 // (`Solver.pressure_mg_level_ratios()` / `CutcellMG::levelRatios()`). Threading `hp` through
7860 // here and through scripts/check_decomposition.py is a follow-up the note does not order.
7861 struct PlanRow {
7862 C3 global, block, ratio;
7863 int ranks;
7864 bool tele;
7865 bool repartition = false; // the stage out of this level is a Repartition (tele is set too)
7866 };
7867 // `decompLevels`/`maxImbalance` are the LEVEL-0 decomposition's parameters (what
7868 // Solver::setDecomposition takes), not the MG level count `nLevels`: predict is a pure function,
7869 // so a caller pre-flighting a coarse-first job must state the depth it will run with. Before the
7870 // env-var retirement these came from a process-global static, which is exactly why they are
7871 // parameters now.
7872 //
7873 // `weights` (optional) are per-cell weights of the global grid, x-fastest (gnx*gny*gnz) -- what
7874 // Solver::rebalanceByWeights takes -- and the forecast is then the hierarchy AFTER that call:
7875 // level 0 is the partition it builds, core's aligned weighted ORB `chooseAlignedWeighted(np, G,
7876 // w)` at its 1.05 budget (`decompLevels` / `maxImbalance` are ignored, as the rebalance ignores
7877 // Solver::setDecomposition), and the stages are those the Solver arms for a weighted dec0
7878 // (setRepartition(true): `chooseStageTarget` with maxBlockCells = the largest level-0 block, so
7879 // a stage may be a Repartition). `*align`, when given, receives that partition's alignment 2^a
7880 // -- rebalanceByWeights' return value. Without weights the forecast is unchanged.
7881 // predict's level-0 partition of the gs grid: core's aligned weighted ORB at its 1.05 budget
7882 // (maxBlockCells = its largest block, as setRepartition arms it; *align = 2^a) with weights,
7883 // else decomposition() (*align = 1).
7884 static peclet::core::decomp::BlockDecomposer<3> predictLevel0(
7885 C3 gs, int np, int decompLevels, double maxImbalance,
7886 const std::vector<peclet::core::Real>* weights, int* align,
7887 peclet::core::Index& maxBlockCells) {
7888 using Dec = peclet::core::decomp::BlockDecomposer<3>;
7889 const int gnx = gs.x, gny = gs.y, gnz = gs.z;
7890 Dec cur;
7891 if (weights) {
7892 if (weights->size() != (std::size_t)gnx * (std::size_t)gny * (std::size_t)gnz)
7893 throw std::invalid_argument(
7894 "predict: weights must hold one value per global cell (gnx*gny*gnz, x-fastest)");
7895 auto c = peclet::core::decomp::chooseAlignedWeighted(
7896 static_cast<std::size_t>(np), peclet::core::IVec<3>{gnx, gny, gnz}, *weights);
7897 cur = std::move(c.dec);
7898 maxBlockCells = peclet::core::decomp::largestBlockCells(cur);
7899 if (align)
7900 *align = 1 << c.a;
7901 } else {
7902 cur = decomposition(static_cast<std::size_t>(np), gnx, gny, gnz, decompLevels, maxImbalance);
7903 if (align)
7904 *align = 1;
7905 }
7906 return cur;
7907 }
7908 // predict's telescoping stage out of level gs (telescope on): initMpi's trigger (a block that
7909 // cannot be lifted, or one below minExtent, while some axis can still halve on several ranks)
7910 // and core's policy. maxBlockCells = 0: flow's sibling-merge search, which never returns a
7911 // Repartition; > 0 for a weighted dec0, as setRepartition arms it. A stage replaces cur and
7912 // marks r.tele (and r.repartition).
7913 static void predictStage(peclet::core::decomp::BlockDecomposer<3>& cur, C3 gs, int minExtent,
7914 peclet::core::Index maxBlockCells, PlanRow& r) {
7915 using Dec = peclet::core::decomp::BlockDecomposer<3>;
7916 const bool canAny = canHalve(gs.x) || canHalve(gs.y) || canHalve(gs.z);
7917 auto liftable = [&](const Dec& d) { return teleLiftable(d, gs); };
7918 const bool blocked = !liftable(cur);
7919 const bool tooSmall =
7920 minExtent > 0 && peclet::core::decomp::minBlockExtent(cur) < (peclet::core::Index)minExtent;
7921 if ((blocked || tooSmall) && canAny && cur.numBlocks() > 1) {
7922 auto t = peclet::core::decomp::chooseStageTarget(cur, peclet::core::IVec<3>{gs.x, gs.y, gs.z},
7923 liftable, minExtent, maxBlockCells);
7924 if (t.kind == peclet::core::decomp::StageKind::SiblingMerge ||
7925 t.kind == peclet::core::decomp::StageKind::Repartition) {
7926 r.repartition = t.kind == peclet::core::decomp::StageKind::Repartition;
7927 cur = std::move(t.dec);
7928 r.tele = true;
7929 }
7930 }
7931 }
7932 // predict's coarsening out of level gs on partition cur: each axis that can halve on every
7933 // block (r.ratio 2 there); returns the next level's extent.
7934 static C3 predictRatio(const peclet::core::decomp::BlockDecomposer<3>& cur, C3 gs, PlanRow& r) {
7935 C3 next = gs;
7936 if (canHalve(gs.x) && evenBlocksOn(cur, 0)) {
7937 r.ratio.x = 2;
7938 next.x = gs.x / 2;
7939 }
7940 if (canHalve(gs.y) && evenBlocksOn(cur, 1)) {
7941 r.ratio.y = 2;
7942 next.y = gs.y / 2;
7943 }
7944 if (canHalve(gs.z) && evenBlocksOn(cur, 2)) {
7945 r.ratio.z = 2;
7946 next.z = gs.z / 2;
7947 }
7948 return next;
7949 }
7950 static std::vector<PlanRow> predict(int gnx, int gny, int gnz, int np, int nLevels,
7951 bool telescope, int minExtent = 4, int decompLevels = 0,
7952 double maxImbalance = 1.05,
7953 const std::vector<peclet::core::Real>* weights = nullptr,
7954 int* align = nullptr) {
7955 using Dec = peclet::core::decomp::BlockDecomposer<3>;
7956 std::vector<PlanRow> rows;
7957 peclet::core::Index maxBlockCells = 0; // 0: sibling merges only (an unweighted dec0)
7958 C3 gs{gnx, gny, gnz};
7959 Dec cur = predictLevel0(gs, np, decompLevels, maxImbalance, weights, align, maxBlockCells);
7960 // doc/mg_depth_policy.md §4.3: nLevels == 0 forecasts the AUTO depth for the SINGULAR operator
7961 // (extent 4, mode auto, all-periodic), as initMpi resolves it.
7962 const bool autoDepth = nLevels == 0;
7963 const int nLevelsCap = autoDepth ? kAutoMaxLevels : nLevels;
7964 const int perBc[6] = {0, 0, 0, 0, 0, 0};
7965 for (int L = 0; L < nLevelsCap; ++L) {
7966 PlanRow r;
7967 r.global = gs;
7968 r.ranks = (int)cur.numBlocks();
7969 r.block = C3{(int)cur.sizes()[0][0], (int)cur.sizes()[0][1], (int)cur.sizes()[0][2]};
7970 r.tele = false;
7971 r.ratio = C3{1, 1, 1};
7972 C3 next = gs;
7973 const bool autoStop =
7974 autoDepth && L + 1 >= kAutoMinLevels && bottomAdmissible(gs, 4, false, -1, perBc);
7975 if (L + 1 < nLevelsCap && !autoStop) {
7976 if (telescope)
7977 predictStage(cur, gs, minExtent, maxBlockCells, r);
7978 next = predictRatio(cur, gs, r);
7979 }
7980 rows.push_back(r);
7981 if (next.x == gs.x && next.y == gs.y && next.z == gs.z)
7982 break;
7983 gs = next;
7984 cur = cur.coarsened(peclet::core::IVec<3>{r.ratio.x, r.ratio.y, r.ratio.z});
7985 }
7986 return rows;
7987 }
7988 // The hierarchy initMpi BUILT, in predict()'s row format -- the oracle predict is tested
7989 // against. Rank 0 holds every level (it is the root of every stage), so there this is the whole
7990 // table; a rank idling below a stage gets the levels it holds.
7991 std::vector<PlanRow> builtPlan() const {
7992 std::vector<PlanRow> rows;
7993 for (const Level& l : lv_) {
7994 PlanRow r;
7995 r.global = l.gdim;
7996 r.block = l.inner;
7997 r.ratio = l.ratio;
7998 r.ranks = 1;
7999 if (l.comm != MPI_COMM_NULL)
8000 MPI_Comm_size(l.comm, &r.ranks);
8001 r.tele = (bool)l.tele;
8002 r.repartition = l.tele && l.tele->repartition();
8003 rows.push_back(r);
8004 }
8005 return rows;
8006 }
8007#endif // PECLET_FLOW_MPI (predict)
8008 bool telescope() const { return telescope_; }
8009 void setTelescopeForceLevel(int L) { teleForce_ = L; } // tests only; -1 = never force
8010 void setTelescopeMinExtent(int e) { teleMinExtent_ = e; }
8012 void setRepartition(bool on) { repartition_ = on; }
8013 bool repartition() const { return repartition_; }
8014 // Number of levels THIS rank holds (fewer than the hierarchy's on a rank idling below a
8015 // telescope point) and the hierarchy's rank count per level (replicated).
8016 int localLevels() const { return (int)lv_.size(); }
8017 int agglomerationMode() const { return agglomMode_; }
8018 void setGraphAmgBottom(bool on) {
8019 agglomMode_ = on ? 1 : 0;
8020 amg_.reset();
8021 }
8022 // Engine selection for an agglomerated bottom (§13 D-5, §14 H-1): kBottomAuto = the FCG bottom
8023 // preconditioned by the direct factor wherever directBottomIneligible() is null (every backend
8024 // since §14 H-1), GraphAMG otherwise; kBottomDirect = that engine or a raise naming the failed
8025 // condition; kBottomAlgebraic = GraphAMG always (the A/B instrument).
8026 enum : int { kBottomAuto = 0, kBottomDirect = 1, kBottomAlgebraic = 2 };
8027 void setBottomSolver(int m) { bottomSolver_ = m; }
8028 int bottomSolver() const { return bottomSolver_; }
8029 // Test hooks (tests/kokkos/test_bottom_direct.cpp). Since §14 H-1 every backend builds the
8030 // bottom's storage at init (single rank); `bottomForceForTest` builds it (and labels the
8031 // components) if it is missing.
8032 bool bottomConnected() const { return bottomConnected_; }
8033 int bottomComponents() const { return bottomNComp_; }
8035 if (!bottomStore_) {
8038 }
8039 }
8040 // §13 hooks.
8041 // `directFactorForTest<FR>`: a fresh factor of the bottom in FR arithmetic (team T, 0 = the
8042 // default), `*Tused` = the team size it ran with; `teamAlgorithm`: by the team algorithm even on
8043 // a host backend (the host schedule's oracle, U8). `directApplyForTest`: z = M(r) by that factor
8044 // through the FCG kernel's precondition-only path (`noMean`: without the component means'
8045 // removal; `teamAlgorithm`: M by the team schedule even on a host backend, the lane schedule's
8046 // oracle, U9); returns the team size. `directSolveForTest`: the production solve (FP32 factor,
8047 // lazily refactored) on the bottom's rhs; returns the inner iterations.
8048 const BottomPlanes& directPlanes() const { return dirPlanes_; }
8049 template <class FR>
8051 int* Tused = nullptr, bool teamAlgorithm = false) {
8052 joinPrefactor();
8054 const int T = launchDirectFactor(D, team, tauPiv0, true, teamAlgorithm);
8055 Kokkos::fence();
8056 if (Tused)
8057 *Tused = T;
8058 return D;
8059 }
8060 template <class FR>
8062 bool noMean = false, bool teamAlgorithm = false) {
8063 const int T = launchDirectKernel(D, true, team, noMean, z, r, true, teamAlgorithm);
8064 Kokkos::fence();
8065 return T;
8066 }
8069 int it = 0;
8070 Kokkos::deep_copy(it, Kokkos::subview(bottomInfo_, 0));
8071 return it;
8072 }
8073 // §14 H-1 (U3 on a host backend): refactor and solve the bottom's rhs at team size `team`
8074 // (clamped to team_size_max), `*Tused` = the size both launches ran with (-1 if they differ);
8075 // returns the inner iterations. The production team sizes are re-probed at the next solve.
8076 int directSolveTeamForTest(int team, int* Tused = nullptr) {
8077 joinPrefactor();
8078 const int Tf = launchDirectFactor(dir_, team, dirPivotTol_);
8079 const int Ts = launchDirectKernel(dir_, false, team, false);
8080 bottomFlagPending_ = true;
8081 Kokkos::fence();
8082 if (Tused)
8083 *Tused = (Tf == Ts) ? Ts : -1;
8084 dirTeam_ = 0;
8085 dirFacTeam_ = 0;
8086 facStale_ = true;
8087 int it = 0;
8088 Kokkos::deep_copy(it, Kokkos::subview(bottomInfo_, 0));
8089 return it;
8090 }
8091 int directRestarts() const {
8092 joinPrefactor();
8093 auto h = Kokkos::create_mirror_view_and_copy(Kokkos::HostSpace(), dir_.stat);
8094 return h(1);
8095 }
8096 void directPivotTolForTest(double t) { dirPivotTol_ = t; }
8097#ifdef PECLET_FLOW_BOTTOM_PROBE
8098 // P2 (doc/vof_gpu_coarse_tail_design.md §5.2): the factor's per-phase clock ticks, accumulated
8099 // over every factor launch since the View was created (bench_bottom_factor only).
8100 Kokkos::View<long long*, CCMem> bottomProbe_;
8101#endif
8103 joinPrefactor();
8104 facStale_ = true;
8105 }
8106
8107 private:
8108};
8109
8110} // namespace peclet::flow
8111
8112#endif // PECLET_FLOW_MAC_CUTCELL_MG_HPP
void debugSetEigenScale(double s)
void fcgNotePr(int it, double beta, double rznew, double rzcross, bool trace)
void gpMatvec(Level &l0, CCField y, CCField q, const GpOverlayReal< MReal > &ov, int nOv, C3 nn)
int solveBiCGStab(CCField b, CCField x, CCField r, CCField rh, CCField p, CCField v, CCField t, CCField z, CCField z2, int maxit, double rtol, int pre, int post, int bottom, const GpOverlayReal< MReal > &ov, int nOv, C3 nn)
double maxabsLocal(Level &lv, CCField a)
int solveFCGAttempt(CCField b, CCField x, CCField r, CCField p, CCField z, CCField zp, CCField Ap, int maxit, double rtol, int pre, int post, int bottom, const StarOverlay *star, int nStar, C3 nnStar)
void meanSubtractHostCounted(Level &lv, CCField f, bool stopGuard)
void applyNeumannGhost(const Level &lv, CCField x, int g=G)
static std::string depthRequestLabel(int nLevels)
double matvecPAp(Level &l0, CCField Ap, CCField p, const StarOverlay *star, int nStar, C3 nnStar)
Kokkos::View< double *, PinnedHost > kgp_
void axpy(CCField y, double a, CCField x)
static constexpr int kGuessPacket
static int directTeam(const K &k, int team, bool probe, std::size_t scratch=0, int hostTeam=kBottomHostTeam)
static constexpr int kLanczosSteps
void exitFp32(Level &l0, CCField zz, CCField rr, double s, int k, CCField p)
Kokkos::View< double, PinnedHost > kcz_
void fillLocal(Level &lv, CCField f)
double residualNorm(CCField b, CCField x, CCField r, CCField Ap)
const BottomPlanes & directPlanes() const
void applyOutflowGhost(const Level &lv, CCField x, int g=G)
void setStrictPressure(bool on)
Throw instead of reporting when the preconditioner returns a non-finite correction.
bool fusedWrapSmooth(const Level &lv) const
void removeMean(Level &lv, CCField f, bool stopGuard=false)
double cgTrueResidual(CCField b, CCField x, CCField r, CCField Ap, const StarOverlay *star=nullptr, int nStar=0, C3 nnStar=C3{0, 0, 0})
void scale(CCField y, double a)
void eigKeep(CCField &dst, CCField x, const char *label, std::size_t n)
void vcycleFp32Impl(int L, bool sym)
double precondDotDist(CCField z, CCField r)
Kokkos::SharedHostPinnedSpace PinnedHost
void setDebugBreakdown(int which, int iter)
int solvePCGResident(CCField b, CCField x, CCField r, CCField p, CCField z, CCField Ap, int maxit, double rtol, int pre, int post, int bottom, const StarOverlay *star, int nStar, C3 nnStar)
static double amgDot(const std::vector< double > &a, const std::vector< double > &c, std::size_t n)
void addSeedNoise(Level &lv, CCField f, double amp)
int failNonFiniteZ(const char *who, Level &l0, CCField x, int maxit)
static constexpr double kLanczosTol
double maxabsWithLocalSum(Level &lv, CCField a, Kokkos::View< double, PinnedHost > part, double &sum)
bool beginAttemptPrecision(int &maxit)
double guessResidual(Level &l0, CCField b, CCField x, CCField r, CCField Ap, const StarOverlay *star, int nStar, C3 nnStar)
double readSlot(int k) const
void aypx(CCField y, double a, CCField x)
void matvecDotPAp(Level &l0, CCField Ap, CCField p, bool fuse, const StarOverlay *star, int nStar, C3 nnStar)
void fillAxis(Level &lv, CCField f, int axis)
std::string lineAxisLabel(int L) const
int directSolveTeamForTest(int team, int *Tused=nullptr)
int solvePCG(CCField b, CCField x, CCField r, CCField p, CCField z, CCField Ap, int maxit, double rtol, int pre, int post, int bottom, const StarOverlay *star=nullptr, int nStar=0, C3 nnStar=C3{0, 0, 0})
const Level & bottomLv() const
bool pApBreakdown(double pAp)
static int lineAxisTrigger(int L, C3 g, C3 cf, const double hp[3], double theta, const int bc[6], double *aspect)
void precondVcycleFp32(CCField zz, CCField rr, int e, int k, CCField p)
void matvecOverlap(Level &l0, CCField y, CCField v)
const char * directBottomIneligible() const
void setOutflowCoefficient(bool on)
const std::vector< double > & healthLog() const
void setMetric(const double hp[3])
Per-axis cell spacings h_a' = h_a / hRef of the physical domain (doc/anisotropic_metric....
void residentPrecondRz(Level &l0, bool f32, bool fuse, int e, CCField z, CCField r, int it, bool health, bool trace)
double initialResidual(Level &l0, CCField b, CCField x, CCField r, CCField Ap, const StarOverlay *star, int nStar, C3 nnStar)
const char * directBottomIneligibleAll() const
double eigPowerMin(Level &l0, CCField v, CCField w, CCField z, int iters, double shift)
void noteFluidCellsDevice(Level &lv)
void amgMeanZero(std::vector< double > &v) const
CCField workVector(int slot, std::size_t n, const char *label)
bool bottomAdmissibleHere(C3 g) const
void noteBicgExit(int exitCode, int it, int maxit, double r0n, double rnLast, double rtol)
void fill(Level &lv, VField f)
static bool touchesGlobalFace(const Level &lv, int f)
static constexpr double kChebSymShift
std::vector< C3 > levelRatios() const
The per-level coarsening ratio actually chosen (the level table of §5, gate §8.5).
static C3 parityOg(const Level &lv)
void lineSmoothColorFp32(Level &lv, int s, int color)
void eigSeedRhs(Level &l0, CCField srhs, CCConst seed)
static double symTridiagTop(int m, const double *d, const double *e, double *y)
double cgUpdate(Level &l0, CCField x, CCField r, CCField p, CCField Ap, double alpha, bool fuse)
void debugSetFp32Fault(int kind, int at)
void directPivotTolForTest(double t)
void vcycle(int L, bool sym)
Kokkos::View< double, PinnedHost > krd_
const char * fp32VcycleIneligible(bool krylov) const
static constexpr double kBrkPAp
bool globalMean(Level &lv, double sum, long cnt, double &mean)
Kokkos::View< double, CCMem > slot(int k) const
void setSymmetricVcycle(bool on)
A3 (doc/mg_depth_policy.md Amendment A3, WO-S1): the symmetric pressure V-cycle – piecewise-constant ...
void amgCellCouplings(C3 gc, C3 gb, int gid, const double(&bc)[6], AmgRows &o) const
void pcgUpdateSum(Level &l0, CCField x, CCField r, CCField p, CCField Ap)
void amgReport(const AmgRhsAnatomy &a, const std::vector< double > &x, const std::vector< double > &r, int it, double r0, int dbg)
void setOpenness(CCConst ox, CCConst oy, CCConst oz, double idx2, double idy2, double idz2)
void guessMatvec(Level &l0, CCField y, CCField v, const StarOverlay *star, int nStar, C3 nnStar)
void lineSmoothColor(Level &lv, int s, int color)
double eigPowerMax(Level &l0, CCField v, CCField w, CCField z, int iters)
void setProjectedGuess(CCField v1, int hist)
void pcgAmg(std::vector< double > &b, std::vector< double > &x)
void matvecDotTo(Level &l0, CCField y, CCField v, int k)
void setBoundaryConditions(const int bc[6])
void eigBracket(double shift, double mu, double &lmin, double &lmax)
double maxabs(Level &lv, CCField a)
void fp32DecoupledCounts(int L, long &n32, long &n64)
void vcycleImpl(int L, bool sym)
void applyBoundaryOpenness(Level &lv, Level *fine=nullptr)
void dotTo(Level &lv, CCField a, CCField b, int k)
peclet::core::solver::HostCsrOp amgAssembleCsr(const AmgRows &rows) const
std::vector< int > lineAxes() const
void precondVcycleCopy(CCField zz, CCField rr)
void setCoarseGhost(bool on)
Neumann coarse ghost on wall/inflow faces before the prolongation (see bcGhost_).
CCField level0Coefficient(int a) const
static bool bottomAdmissible(C3 g, int extent, bool anchored, int agglomMode, const int bc[6])
bool residentPacketExit(int &it, double rtol, double rref, double r0, bool trace, double &rn)
Kokkos::View< long, CCMem > kcnt_
void setAspectThreshold(double theta)
Anisotropic-coarsening aspect threshold theta (see aspectTheta_).
void copyDotTo(Level &lv, CCField p, CCField r, CCField z, int k)
bool lineRelaxOn(const Level &lv) const
void setRepartition(bool on)
Repartition stages for a weighted level-0 decomposition (see repartition_); before initMpi.
void removeMeanDotTo(Level &lv, int k, CCField p)
void precondVcycle(CCField zz, CCField rr)
double fcgPrecondRz(Level &l0, bool f32, bool fuse, CCField z, CCField r, double rn, CCField p)
void dotPair(Level &lv, CCField a, CCField b, CCField c, double &ab, double &ac)
static constexpr int G
void maskSolid(Level &lv, CCField f)
AmgRhsAnatomy amgRhsAnatomy(const std::vector< double > &b) const
void fp32Reconfigure(bool wasCarriable, bool wasDeferrable)
void residentBetaAypx(CCField pp, CCField zz, std::size_t n)
bool linePeriodic(int s) const
void removeMeanHostCounted(Level &lv, CCField f, bool stopGuard)
int launchDirectFactor(const BottomDirect< FR > &D, int team, double tauPiv0, bool probe=true, bool teamAlgorithm=false, const CCExec &exec=CCExec())
void guessTraceExit(Level &l0, CCField b, CCField x, double rref, double r0w, int it, int hist, const StarOverlay *star, int nStar, C3 nnStar)
static constexpr double kChebBracket
void applyBoundaryOpennessFrom(Level &lv, const CCField *fo, C3 fext, int fg, C3 fratio)
static constexpr int kNSlots
double pcgUpdateMeanMaxDist(Level &l0, CCField x, CCField r, CCField p, CCField Ap, double alpha)
void smoothFp32(Level &lv, int sweeps, bool reverse, bool skipFirst)
void estimateEigenvalues(CCConst seed, double &lmin, double &lmax, int iters, int pre, int post, int bottom, EigenStart start=EigenStart::Cold, double bracket=1.0)
void lin(CCField out, double a, CCField x, double b, CCField y)
double armStopTest(double r0, double rtol)
int solveChebyshev(CCField b, CCField x, int maxit, double rtol, int pre, int post, int bottom, double a, double bnd, bool guard3=false, bool guardGrowth=false)
double dot(Level &lv, CCField a, CCField b)
void fill(Level &lv, CCField f)
static void allocLine(Level &v)
void printAmgBuildCensus(const AmgRows &rows) const
void setStopReference(double ref)
void setSlot(int k, double v)
Kokkos::View< double *, CCMem > ks_
bool hostAllFluid(const Level &lv) const
int directApplyForTest(const BottomDirect< FR > &D, CCField z, CCField r, int team, bool noMean=false, bool teamAlgorithm=false)
double firstPrecondRz(Level &l0, bool f32, bool fuse, int e, CCField z, CCField r, CCField p)
AmgRows amgLocalRows(const Level &lv, C3 gb) const
void graphAmgSolveBottom(Level &lv)
std::vector< int > lineSmoothedLevels() const
static C3 mgChooseRatio(const double H[3], const bool canA[3], bool aniso, double theta)
int launchDirectKernel(const BottomDirect< FR > &D, bool precondOnly, int team, bool noMean, CCField zOut=CCField(), CCField rIn=CCField(), bool probe=true, bool teamAlgorithm=false)
double removeMeanDotDist(Level &lv)
static bool canHalve(int d)
void noteHealth(double rzOld, int it, bool trace, bool f32)
C3 levelRatio(C3 gs, C3 cf, const bool canA[3], C3 &next) const
int solveWithRestart(CCField x, int maxit, Attempt &&attempt)
void setAgglomerationMode(int mode)
void smooth(Level &lv, int sweeps, bool reverse)
void eigApplyT(Level &l0, CCField out, CCField in, CCField w)
bool cgConverged(int &it, double rn, double r0, double rtol, double rref, bool trace)
void applyNeumannGhost(const Level &lv, VField x, int g=G)
void setAgglomerationExtent(int cells)
static const char * bottomLabelWhy(int code)
int solvePCGAttempt(CCField b, CCField x, CCField r, CCField p, CCField z, CCField Ap, int maxit, double rtol, int pre, int post, int bottom, const StarOverlay *star, int nStar, C3 nnStar)
static constexpr bool kHostMemory
double lanczosTop(Level &l0, CCField v, bool ritz)
Kokkos::View< double *, PinnedHost > kpk_
void maxabsTo(Level &lv, CCField a, int k)
void applyNeumannGhostT(const Level &lv, V x, int g)
void printDepthCensus(int nLevels, bool more) const
void setLineRelaxation(bool on)
A2.4 (doc/mg_depth_policy.md, WO-7): zebra line relaxation along the blocked strong axis on the trigg...
void saveOutflowPlanes(Level &lv)
void amgLabelComponents(const AmgRows &rows)
void setExactResidual(bool on)
The exact double flux-form level-0 apply in the residual and the Krylov matvec.
void init(int nx, int ny, int nz, int nLevels)
void setEigenWarm(CCField vmax, CCField vmin)
double pcgPrecondRz(Level &l0, bool f32, bool fuse, CCField z, CCField r, double rn, int k, CCField p)
void matvecGuessDots(Level &l0, CCField y, CCField v, CCField w, CCField r, int kvy, int kvr, int kwy)
double eigSeed(Level &l0, CCField x, CCField src)
void meanSubtractMaxTo(Level &lv, CCField f, int k)
bool caSmooth(const Level &lv) const
void finalRemoveMean(Level &l0, CCField x)
int solveFCG(CCField b, CCField x, CCField r, CCField p, CCField z, CCField zp, CCField Ap, int maxit, double rtol, int pre, int post, int bottom, const StarOverlay *star=nullptr, int nStar=0, C3 nnStar=C3{0, 0, 0})
bool agglomerateAuto(long gx, long gy, long gz) const
void setMeanRemovalScope(bool all)
bool fp32WeightsOk(int L) const
static constexpr int kPacket
static constexpr double kBrkRz
double rhsNorm(CCField b, CCField scratch)
bool precondDotTo(bool f32, bool fuse, int e, int k, CCField z, CCField r, CCField pz)
static C3 boxLo(int g, int m)
void residentUpdate(Level &l0, CCField xx, CCField rr, CCField pp, CCField aa, bool fuse)
long gbIndex(int gid) const
void fillWrap(Level &lv, V f)
void setCommAvoiding(int mask)
Communication-avoiding smoothing mask (kCaMomentum | kCaMg); only kCaMg is read here.
double eigNormalize(Level &l0, CCField x)
StartResidual startResidual(CCField b, CCField x, CCField r, CCField Ap, CCField z, const StarOverlay *star, int nStar, C3 nnStar, bool fused, bool resident)
BottomDirect< FR > directFactorForTest(int team, double tauPiv0=kBottomPivotTol, int *Tused=nullptr, bool teamAlgorithm=false)
static C3 boxHi(C3 e, int g, int m)
void setVcyclePrecision(int mode)
void meanSumHostCounted(Level &lv, CCField f)
double projectedGuess(Level &l0, CCField b, CCField x, CCField r, CCField av1, CCField av2, const StarOverlay *star, int nStar, C3 nnStar, bool fused, double *r0w)
BottomKernel< FR > makeBottomKernel(bool precondOnly)
void debugSetStencilHaloOff(bool on)
flow — directional ghost-cell IBM projection overlay (experimental second staggered IBM).
flow — portable (Kokkos) native per-face domain boundary conditions for the MAC grid.
#define PECLET_FLOW_OMP_SIMD
flow — portable (Kokkos) cut-cell pressure operator + Chorin projection.
flow — the device pressure bottom's direct preconditioner (doc/vof_step_performance_ design....
branch(c, f, a)
dict res
Definition mgd_case.py:488
constexpr int kBottomHostFactorTeam
double cutcellApplyExactCell(const XV &x, const OV &ox, const OV &oy, const OV &oz, long i, long sx, long sy, long sz, long xp, long xm, long yp, long ym, long zp, long zm, double gfx, double gfy, double gfz)
Kokkos::DefaultExecutionSpace CCExec
void mgSaveFacePlane(CCField dst, CCConst src, C3 e, int g, int a, int s)
void ccForRows3(const char *name, C3 lo, C3 hi, F f)
void residualCutcellFace(CCField r, CCConst x, CCConst b, FPC AC, FPC AFX, FPC AFY, FPC AFZ, C3 e, int g)
void cutcellSmoothColorFp32Box(VField x, VConst b, VConst WX, VConst WY, VConst WZ, C3 e, C3 og, int color, C3 lo, C3 hi, C3 exLo, C3 exHi, int wrapMask=0, int g=1)
void applyCutcellOpFaceWrap(CCField y, CCConst x, FPC AC, FPC AFX, FPC AFY, FPC AFZ, C3 e, C3 n, int g)
CcNbrs ccMaskNbrs(int lx, int ly, int lz, C3 n, int g, long i, long sy, long sz, int m)
void applyCutcellOpFace(CCField y, CCConst x, OpV AC, OpV AFX, OpV AFY, OpV AFZ, C3 e, int g)
Kokkos::MDRangePolicy< Exec, Kokkos::Rank< 3, Kokkos::Iterate::Left, Kokkos::Iterate::Left > > MDRange3
3-D range, x (the first index) fastest (both the tile order and the order within a tile).
Definition policy.hpp:36
void cutcellBuildFaceOpCell(const OpV &AC, const OpV &AFX, const OpV &AFY, const OpV &AFZ, const OV &ox, const OV &oy, const OV &oz, long i, long sx, long sy, long sz, double gfx, double gfy, double gfz, bool diag)
void mgRestoreFacePlane(CCField dst, CCConst src, C3 e, int g, int a, int s)
void prolongConstAdd(CCField fine, CCConst coarse, C3 fext, C3 cext, int gf, int gc, C3 finner, C3 ratio)
void bcSetOpenness(BField oa, B3 ext, int g, int a, int s, double val)
Definition mac_bc.hpp:488
void restrictAvgZeroX(CCField coarse, CCField coarseX, CCConst fine, C3 cext, C3 fext, int gc, int gf, C3 cinner, C3 ratio)
void cutcellResidualFaceCell(const RV &r, const XV &x, const BV &b, const OpV &AC, const OpV &AFX, const OpV &AFY, const OpV &AFZ, long i, long sx, long sy, long sz, long xp, long xm, long yp, long ym, long zp, long zm)
void prolongAdd(CCField fine, CCConst coarse, C3 fext, C3 cext, int gf, int gc, C3 finner, C3 ratio)
constexpr int kBottomHostTeam
void bcZeroPressureGhost(BField phi, B3 ext, int g, int a, int s)
Definition mac_bc.hpp:321
void prolongFp32FromD(VField fine, CCConst coarse, C3 fext, C3 cext, int gf, int gc, C3 finner, C3 ratio)
void cutcellSmoothFaceCell(const PV &phi, const BV &b, const OpV &AC, const OpV &AFX, const OpV &AFY, const OpV &AFZ, long i, long sx, long sy, long sz, long xp, long xm, long yp, long ym, long zp, long zm)
void prolongAddCell(const FV &fine, const CV &coarse, C3 fext, C3 cext, int gf, int gc, C3 ratio, int ifx, int ify, int ifz)
Kokkos::View< const double *, CCMem > CCConst
void cutcellSmoothColorBoxFace(CCField phi, CCConst b, OpV AC, OpV AFX, OpV AFY, OpV AFZ, C3 e, C3 og, int color, C3 rlo, C3 rhi, C3 slo, C3 shi, int wrapMask=0, int g=1)
void coarsenOpenAvg(CCField oxc, CCField oyc, CCField ozc, CCConst oxf, CCConst oyf, CCConst ozf, C3 cext, C3 fext, int gc, int gf, C3 cinner, C3 ratio)
void residualFp32Box(VField r, VConst x, VConst b, VConst WX, VConst WY, VConst WZ, C3 e, C3 lo, C3 hi, C3 exLo, C3 exHi, int wrapMask=0, int g=1)
void ccReduce3(const char *name, C3 lo, C3 hi, F f, R &&... reducers)
void residualCutcell(CCField r, CCConst x, CCConst b, FPC AC, FPC AW, FPC AE, FPC AS, FPC AN, FPC AB, FPC AT, C3 e, int g)
void applyCutcellOpBoxFace(CCField y, CCConst x, OpV AC, OpV AFX, OpV AFY, OpV AFZ, C3 e, C3 rlo, C3 rhi, C3 slo, C3 shi, int wrapMask=0, int g=1)
void residualFp32Wrap(VField r, VConst x, VConst b, VConst WX, VConst WY, VConst WZ, C3 e, C3 n, int g)
void mgCoarsenFacePlane(CCField oc, CCConst of, C3 cext, C3 fext, int gc, int gf, C3 cinner, C3 ratio, int a, int s)
BottomPlanes bottomChoosePlanes(C3 inner, const int bc[6])
void applyCutcellOpExact(CCField y, CCConst x, CCConst ox, CCConst oy, CCConst oz, C3 e, int g, double gfx, double gfy, double gfz)
void residualCutcellBoxFace(CCField r, CCConst x, CCConst b, FPC AC, FPC AFX, FPC AFY, FPC AFZ, C3 e, C3 rlo, C3 rhi, C3 slo, C3 shi, int wrapMask=0, int g=1)
constexpr int kBottomCap
void gpApplyDelta(CCField y, CCConst x, const GpOverlayReal< Real > &ov, int nOv, C3 nn, C3 extY, int gbY, C3 extX, int gbX, bool useGhost=false)
Overlay matvec correction: y(r) = rho_r * (y(r) + closure-face phi terms), where y currently holds th...
void cutcellResidualCell(const RV &r, const XV &x, const BV &b, const OpV &AC, const OpV &AW, const OpV &AE, const OpV &AS, const OpV &AN, const OpV &AB, const OpV &AT, long i, long xp, long xm, long yp, long ym, long zp, long zm)
void restrictFp32ToDZeroX(CCField coarse, CCField coarseX, VConst fine, C3 cext, C3 fext, int gc, int gf, C3 cinner, C3 ratio)
constexpr double kBottomTau
Kokkos::View< const MReal *, CCMem > FPC
void restrictFp32ZeroX(VField coarse, VField coarseX, VConst fine, C3 cext, C3 fext, int gc, int gf, C3 cinner, C3 ratio)
constexpr int kCaDefault
void prolongFp32(VField fine, VConst coarse, C3 fext, C3 cext, int gf, int gc, C3 finner, C3 ratio)
constexpr int kAutoMaxLevels
void ccBoxShellRuns(const char *name, C3 rlo, C3 rhi, C3 slo, C3 shi, Run run)
void fp32AddDouble(VField f, CCConst d, C3 e, int g)
void ccWrapForPeeled(const char *name, C3 e, C3 n, int g, const Cell &cell)
void fp32ToDouble(CCField d, VConst f, C3 e)
void buildCutcellOpFace(OpV AC, OpV AFX, OpV AFY, OpV AFZ, CCConst ox, CCConst oy, CCConst oz, C3 e, int gb, double gfx, double gfy, double gfz)
void applyCutcellOpExactWrap(CCField y, CCConst x, CCConst ox, CCConst oy, CCConst oz, C3 e, C3 n, int g, double gfx, double gfy, double gfz)
void residualCutcellFaceWrap(CCField r, CCConst x, CCConst b, FPC AC, FPC AFX, FPC AFY, FPC AFZ, C3 e, C3 n, int g)
void buildCutcellOpFaceFp32(OpV AC, OpV AFX, OpV AFY, OpV AFZ, WV WX, WV WY, WV WZ, CCConst ox, CCConst oy, CCConst oz, C3 e, int gb, double gfx, double gfy, double gfz, int fp64, int *bad)
Kokkos::View< VReal *, CCMem > VField
GpOverlayT< CCMem, Real > GpOverlayReal
void applyCutcellOpExactBox(CCField y, CCConst x, CCConst ox, CCConst oy, CCConst oz, C3 e, C3 rlo, C3 rhi, C3 slo, C3 shi, double gfx, double gfy, double gfz, int wrapMask=0, int g=1)
CcNbrs ccWrapNbrs(int lx, int ly, int lz, C3 n, int g, long i, long sy, long sz)
void cutcellSmoothColorFace(CCField phi, CCConst b, OpV AC, OpV AFX, OpV AFY, OpV AFZ, C3 e, C3 og, int g, int color)
void lineRelaxColorFace(CCField x, CCConst b, OpV AC, OpV AFX, OpV AFY, OpV AFZ, CCField c, CCField y, CCField z, C3 e, C3 og, int g, int s, bool periodic, int wrapMask, int color)
void residualCutcellBox(CCField r, CCConst x, CCConst b, FPC AC, FPC AW, FPC AE, FPC AS, FPC AN, FPC AB, FPC AT, C3 e, C3 rlo, C3 rhi, C3 slo, C3 shi)
Kokkos::View< double *, CCMem > CCField
void ccFor3(const char *name, C3 lo, C3 hi, F f)
Kokkos::View< MReal *, CCMem > FPV
void ccMaskRow(int ly, int lz, int lx0, int x1, int step, C3 e, C3 n, int g, int m, const Cell &cell)
void meanSubtractCell(const FV &f, const AV &ac, long i, double mean)
constexpr long kBottomMaxCells
void restrictAvg(CCField coarse, CCConst fine, C3 cext, C3 fext, int gc, int gf, C3 cinner, C3 ratio)
constexpr int kBottomMaxComponents
constexpr bool kAnchoredFollowsGrid
void coarsenOpenAvgCell(const CV &oxc, const CV &oyc, const CV &ozc, const FV &oxf, const FV &oyf, const FV &ozf, C3 cext, C3 fext, int gc, int gf, C3 ratio, int icx, int icy, int icz)
constexpr double kBottomPivotTol
void prolongConstAddCell(const FV &fine, const CV &coarse, C3 fext, C3 cext, int gf, int gc, C3 ratio, int ifx, int ify, int ifz)
void lineRelaxColorFp32(VField x, VConst b, VConst WX, VConst WY, VConst WZ, VField c, VField y, VField z, C3 e, C3 og, int g, int s, bool periodic, int wrapMask, int color)
constexpr int kAutoMinLevels
void ccReduce3Lanes(const char *name, C3 lo, C3 hi, F f, R &&... reducers)
void cutcellSmoothColorFaceWrap(CCField phi, CCConst b, FPC AC, FPC AFX, FPC AFY, FPC AFZ, C3 e, C3 n, C3 og, int g, int color)
void bcNeumannGhostT(FV f, B3 ext, int g, int a, int s)
Definition mac_bc.hpp:247
void ccWrapRowPeeled(int ly, int lz, C3 e, C3 n, int g, int lx0, int step, const Cell &cell)
void entryFp32(VField xf, VField rhsf, CCConst rr, VConst WX, VConst WY, VConst WZ, double sigma, C3 e, C3 og, int g, int color, bool smoothFirst)
void cutcellSmoothColorFp32Wrap(VField x, VConst b, VConst WX, VConst WY, VConst WZ, C3 e, C3 n, C3 og, int g, int color)
bool hostRunSerial(long cells)
double cutcellApplyFaceCell(const XV &x, const OpV &AC, const OpV &AFX, const OpV &AFY, const OpV &AFZ, long i, long sx, long sy, long sz, long xp, long xm, long yp, long ym, long zp, long zm)
Kokkos::MDRangePolicy< Exec, Kokkos::Rank< 2, Kokkos::Iterate::Left, Kokkos::Iterate::Left > > MDRange2
2-D range, first index fastest (both the tile order and the order within a tile).
Definition policy.hpp:31
void prolongConstFp32(VField fine, VConst coarse, C3 fext, C3 cext, int gf, int gc, C3 finner, C3 ratio)
void restrictAvgCell(const CV &coarse, const FV &fine, C3 cext, C3 fext, int gc, int gf, C3 ratio, int icx, int icy, int icz)
void prolongConstFp32FromD(VField fine, CCConst coarse, C3 fext, C3 cext, int gf, int gc, C3 finner, C3 ratio)
Kokkos::View< const VReal *, CCMem > VConst
void starApplyDelta(CCField y, CCConst x, const StarOverlay &ov, int nOv, C3 nn, C3 extY, int gY, C3 extX, int gX, bool exact)
y += S_star x over the inner cells of the (extY, gY) block, x read from the (extX,...
Definition post.py:1
dict A
Definition post.py:33
int m
Definition post.py:35
tuple rc
Definition post.py:37
t
Definition post.py:21
one(n, rho_ratio, mu_ratio, stress, steps, adv, dtf, grav=False, sigma="none")
report(name, d)
dict rows
Definition summarize.py:38
list ms
Definition summarize.py:60
Definition sweep.py:1
flow — the multidimensional iteration policies: iteration order follows storage.
flow — Design B of the fluid-only collocated constraint (route 2b): Kron (star-mesh) elimination of s...
int y
int x
int z
OverlayScope(bool &f, bool on)
static BottomDirect allocate(const BottomPlanes &p, C3 ext)
static std::size_t scratchBytes(int b)
static double teamMax(const Member &t, int n, const F &f)
static double teamSum(const Member &t, int n, const F &f)
void removeMeanBottom(const Member &t, const CCField &f) const
Kokkos::View< const int *, CCMem > comp
Kokkos::View< int *, CCMem > info
void operator()(const Member &t) const
void applyM(const Member &t, const CCField &R, const CCField &Z, const CCField *keep) const
static int nInner(const BottomLevel &l)
static constexpr bool kHostLane
double dot(const Member &t, const BottomLevel &l, const CCField &a, const CCField &c) const
BottomDirect< FacReal > dir
Kokkos::View< double *, CCMem > ks
Kokkos::View< double *, CCMem > cmean
Kokkos::TeamPolicy< CCExec >::member_type Member
Kokkos::View< const long *, CCMem > ccnt
static long cell(const BottomLevel &l, int q, int &lx, int &ly, int &lz)
static int nExt(const BottomLevel &l)
Kokkos::View< int *, CCMem > kc
Kokkos::View< long *, CCMem > cnt
Kokkos::TeamPolicy< CCExec >::member_type Member
Kokkos::View< double *, CCMem > aug
Kokkos::View< int *, CCMem > nc
void operator()(const Member &t) const
Kokkos::View< int *, CCMem > tmp
long cell(int q, int &lx, int &ly, int &lz) const
Kokkos::View< int *, CCMem > comp
int sweep(const Member &t, const Kokkos::View< int *, CCMem > &src, const Kokkos::View< int *, CCMem > &dst) const
std::vector< std::uint8_t > solid
Kokkos::View< VReal *, CCMem > resf
Kokkos::View< VReal *, CCMem > WY
Kokkos::View< VReal *, CCMem > lnzf
Kokkos::View< VReal *, CCMem > lncf
Kokkos::View< VReal *, CCMem > WX
Kokkos::View< VReal *, CCMem > WZ
Kokkos::View< VReal *, CCMem > xf
Kokkos::View< VReal *, CCMem > lnyf
Kokkos::View< long, CCMem > nFluidDev
Kokkos::View< VReal *, CCMem > rhsf
One entry per eliminated solid-centered cell: packed INNER flat index + the apertures of its (up to 6...
static double val(long gi)
Definition symconv.cpp:27
static constexpr int N
Kokkos::View< const double *, CCMem > CCConst
Kokkos::View< double *, CCMem > CCField
static constexpr int G
peclet::core::decomp::BlockDecomposer< 3 > Dec
static constexpr double AC
Kokkos::View< double *, peclet::flow::CCMem > OpV
static constexpr double F
Kokkos::View< float *, IMem > FV
static int run(int bc)
static constexpr double R
static std::vector< peclet::core::Real > weights(int kind, Grid3 g)
static double mean(const std::vector< double > &a)