flow 1.4.0
Kokkos cut-cell IBM incompressible Navier-Stokes solver + pnm pore extraction
Loading...
Searching...
No Matches
mg_dense_precond.cpp
Go to the documentation of this file.
1// WO-M — DENSE ASSEMBLY OF THE MULTIGRID V-CYCLE PRECONDITIONER.
2//
3// Why this exists. WO-H closed the wall-bounded MG-PCG stall and, in doing so, measured a
4// *residual* failure it could not fix: on a high-contrast coefficient the V-cycle preconditioner M
5// goes INDEFINITE (a negative LDL pivot of sym(M) from density ratio ~1e3 walled and ~1e4 even
6// fully periodic), which no choice of the CG beta survives. WO-H attributed that to the arithmetic
7// coarsening of the face coefficient (`coarsenOpenAvg`) — VOF_PLAN's S3 item. But every one of
8// those measurements was taken on a hierarchy whose operator is stored in FLOAT
9// (`mac_cutcell_mg.hpp` MReal), and float rounding breaks the singular row-sum identity A*1 = 0 at
10// ~eps_f32 per row; under three decades of coefficient contrast that defect is ~1e-4 relative to
11// the small couplings. So a float-perturbed near-singular operator is a fully sufficient
12// ALTERNATIVE explanation for the same negative pivot, and nothing in the record separates the two.
13//
14// This probe separates them. It assembles M column by column exactly as CG builds it — one
15// mean-removed unit basis vector in, one symmetric V-cycle, the result out — on the SAME code path
16// the CG drivers use, and writes the dense matrix to disk. Building this file twice, with and
17// without -DPECLET_FLOW_OPERATOR_DOUBLE, changes ONLY the operator storage precision. If the
18// negative pivot disappears in double, the S3 coefficient-coarsening theory loses its evidence; if
19// it survives, S3 stands as an independent mechanism.
20//
21// It also assembles the FINE operator A densely (same unit-vector trick) so the mechanism claim
22// itself — the per-row defect of A*1 = 0 — is a measured number rather than an argument.
23//
24// Analysis (skew, LDL pivots, spectrum of sym(M) on the mean-free subspace) is done by the sibling
25// mg_precond_analyze.py: LAPACK gives an unambiguous smallest eigenvalue, where an unpivoted LDL on
26// a matrix that is singular BY CONSTRUCTION (the constant mode) can report a sign-noise pivot at
27// 1e-12 that means nothing.
28//
29// Usage:
30// ./mg_dense_precond --n 8 --levels 3 --geom periodic|wallz --ratio 1e3 --out M.bin
31// ./mg_dense_precond --sweep --outdir <dir> (the whole geom x ratio battery)
32// ... --precision fp32 M = the FP32 V-cycle (doc/vof_projection_cost_design.md §4, G-D2),
33// written as M_vf32_*; compare with mg_precond_fp32cmp.py
34#include <cmath>
35#include <cstdint>
36#include <cstdio>
37#include <cstdlib>
38#include <cstring>
39#include <Kokkos_Core.hpp>
40#include <string>
41#include <vector>
42
43#include "mac_cutcell_mg.hpp"
44
45namespace {
46
51
52struct Config {
53 int n = 8;
54 int levels = 3;
55 int geom = 0; // 0 = fully periodic, 1 = walls +-z
56 double ratio = 1; // density contrast of a sharp mid-height z-slab (1 = uniform coefficient)
57 bool fp32 =
58 false; // --precision fp32: M = the FP32 V-cycle (doc/vof_projection_cost_design.md §4)
59};
60
61const char* geomName(int g) {
62 return g == 0 ? "periodic" : "wallz";
63}
64
65// Write a dense row-major n x n double matrix with a 3-int64 header {magic, rows, cols}.
66void writeMatrix(const std::string& path, const std::vector<double>& a, long n) {
67 FILE* f = std::fopen(path.c_str(), "wb");
68 if (!f) {
69 std::fprintf(stderr, "mg_dense_precond: cannot open %s for writing\n", path.c_str());
70 return;
71 }
72 const std::int64_t hdr[3] = {0x50434D47444E5331LL, n, n}; // "PCMGDNS1"
73 std::fwrite(hdr, sizeof(std::int64_t), 3, f);
74 std::fwrite(a.data(), sizeof(double), (size_t)n * (size_t)n, f);
75 std::fclose(f);
76}
77
78// One configuration: build the hierarchy, assemble A and M densely, report and write.
79void run(const Config& cfg, const std::string& outdir) {
80 const int nx = cfg.n, ny = cfg.n, nz = cfg.n;
81 const int G = CutcellMG::G;
82 const C3 ext{nx + 2 * G, ny + 2 * G, nz + 2 * G};
83 const long sy = ext.x, sz = (long)ext.x * ext.y;
84 const long next = (long)ext.x * ext.y * ext.z;
85 const long n = (long)nx * ny * nz;
86
87 CutcellMG mg;
88 mg.init(nx, ny, nz, cfg.levels);
89 int bc[6] = {0, 0, 0, 0, 0, 0};
90 if (cfg.geom == 1) {
91 bc[4] = 1; // -z wall
92 bc[5] = 1; // +z wall
93 }
95 if (cfg.fp32)
97
98 // Face coefficients c_f = open_f * rho0/rho_f, arithmetic face mean of rho (buildRhoCoeff), from
99 // a SHARP mid-height slab: rho = rho0 below, rho0*ratio above. Uniform openness 1 — the geometry
100 // is a box, so the ONLY thing varying is the coefficient contrast this probe is about.
101 std::vector<double> rho((size_t)next, 1.0);
102 for (int z = 0; z < ext.z; ++z) {
103 // periodic wrap of the ghost planes onto the inner slab pattern
104 int zi = ((z - G) % nz + nz) % nz;
105 const double r = (zi >= nz / 2) ? cfg.ratio : 1.0;
106 for (int y = 0; y < ext.y; ++y)
107 for (int x = 0; x < ext.x; ++x)
108 rho[(size_t)(x + (long)y * sy + (long)z * sz)] = r;
109 }
110 std::vector<double> hcx((size_t)next, 0.0), hcy((size_t)next, 0.0), hcz((size_t)next, 0.0);
111 for (int z = G; z < ext.z - G; ++z)
112 for (int y = G; y < ext.y - G; ++y)
113 for (int x = G; x < ext.x - G; ++x) {
114 const long i = x + (long)y * sy + (long)z * sz;
115 hcx[(size_t)i] = 1.0 / (0.5 * (rho[(size_t)i] + rho[(size_t)(i - 1)]));
116 hcy[(size_t)i] = 1.0 / (0.5 * (rho[(size_t)i] + rho[(size_t)(i - sy)]));
117 hcz[(size_t)i] = 1.0 / (0.5 * (rho[(size_t)i] + rho[(size_t)(i - sz)]));
118 }
119 CCField cx("cx", next), cy("cy", next), cz("cz", next);
120 auto hx = Kokkos::create_mirror_view(cx), hy = Kokkos::create_mirror_view(cy),
121 hz = Kokkos::create_mirror_view(cz);
122 for (long i = 0; i < next; ++i) {
123 hx(i) = hcx[(size_t)i];
124 hy(i) = hcy[(size_t)i];
125 hz(i) = hcz[(size_t)i];
126 }
127 Kokkos::deep_copy(cx, hx);
128 Kokkos::deep_copy(cy, hy);
129 Kokkos::deep_copy(cz, hz);
130 mg.setOpenness(CCConst(cx), CCConst(cy), CCConst(cz), 1.0, 1.0, 1.0);
131
132 CutcellMG::Level& l0 = mg.level(0);
133 CCField v("v", next), y("y", next);
134 // Put the V-cycle on the PRODUCTION smoothing schedule. pre_/post_/bottom_ are private and are
135 // written by the Krylov entry points, so one zero-iteration solvePCG with the solver's own
136 // (2, 2, 12) is the setter — IbmSolver::project calls solvePCG/solveFCG with exactly those.
137 {
138 CCField s0("s0", next), s1("s1", next), s2("s2", next), s3("s3", next), s4("s4", next);
139 mg.solvePCG(s0, s1, s2, s3, s4, y, /*maxit=*/0, 1e-8, 2, 2, 12);
140 }
141 auto hv = Kokkos::create_mirror_view(v), hy2 = Kokkos::create_mirror_view(y);
142
143 std::vector<long> idx((size_t)n); // inner ordinal -> extended linear index
144 for (int k = 0; k < nz; ++k)
145 for (int j = 0; j < ny; ++j)
146 for (int i = 0; i < nx; ++i)
147 idx[(size_t)(i + (long)j * nx + (long)k * nx * ny)] =
148 (i + G) + (long)(j + G) * sy + (long)(k + G) * sz;
149
150 std::vector<double> A((size_t)n * (size_t)n, 0.0), M((size_t)n * (size_t)n, 0.0);
151
152 // --- the fine operator A, column by column (matvecOverlap is what solvePCG calls) -------------
153 for (long c = 0; c < n; ++c) {
154 Kokkos::deep_copy(hv, 0.0);
155 hv(idx[(size_t)c]) = 1.0;
156 Kokkos::deep_copy(v, hv);
157 mg.matvecOverlap(l0, y, v);
158 Kokkos::deep_copy(hy2, y);
159 for (long r = 0; r < n; ++r)
160 A[(size_t)r * (size_t)n + (size_t)c] = hy2(idx[(size_t)r]);
161 }
162
163 // --- the preconditioner M, column by column ---------------------------------------------------
164 // Exactly solvePCG's `precond` lambda, preceded by the mean removal CG applies to the residual
165 // before every preconditioner application (removeMean(l0, r) in the CG loop).
166 // --precision fp32 (G-D2, §13): the FP32 V-cycle as the eligible PCG applies it --
167 // precondVcycleFp32(z, r, e) with e = ilogb(max|r|), the power-of-two input scaling of §4.4.4.
168 if (cfg.fp32) {
169 if (const char* why = mg.fp32VcycleIneligible(true)) {
170 std::fprintf(stderr, "mg_dense_precond --precision fp32: not eligible: %s\n", why);
171 std::exit(2);
172 }
173 CCField z("z", next);
174 for (long c = 0; c < n; ++c) {
175 Kokkos::deep_copy(hv, 0.0);
176 hv(idx[(size_t)c]) = 1.0;
177 Kokkos::deep_copy(v, hv);
178 mg.removeMean(l0, v);
179 const double rn = mg.maxabs(l0, v);
180 mg.precondVcycleFp32(z, v, std::ilogb(rn), -1, CCField());
181 Kokkos::deep_copy(hy2, z);
182 for (long r = 0; r < n; ++r)
183 M[(size_t)r * (size_t)n + (size_t)c] = hy2(idx[(size_t)r]);
184 }
185 }
186 for (long c = 0; c < (cfg.fp32 ? 0 : n); ++c) {
187 Kokkos::deep_copy(hv, 0.0);
188 hv(idx[(size_t)c]) = 1.0;
189 Kokkos::deep_copy(v, hv);
190 mg.removeMean(l0, v);
191 Kokkos::deep_copy(l0.rhs, v);
192 Kokkos::deep_copy(l0.x, 0.0);
193 mg.vcycle(0, /*sym=*/true);
194 Kokkos::deep_copy(hy2, l0.x);
195 for (long r = 0; r < n; ++r)
196 M[(size_t)r * (size_t)n + (size_t)c] = hy2(idx[(size_t)r]);
197 }
198
199 // --- the mechanism number: the per-row defect of A*1 = 0 ---------------------------------------
200 // Every interior row of the singular Poisson operator sums to zero EXACTLY in exact arithmetic
201 // (the diagonal is minus the sum of the off-diagonals). Float storage breaks that at ~eps_f32
202 // relative to the LARGEST coefficient in the row; on a row that mixes a large and a tiny coupling
203 // the same absolute defect is ~eps_f32 * contrast relative to the TINY one. Report both norms.
204 double rowsumAbs = 0, rowsumRelMax = 0, rowsumRelMin = 0;
205 for (long r = 0; r < n; ++r) {
206 double s = 0, mx = 0, mn = 1e300;
207 for (long c = 0; c < n; ++c) {
208 const double a = A[(size_t)r * (size_t)n + (size_t)c];
209 s += a;
210 if (c != r && a != 0.0) {
211 mx = std::fmax(mx, std::fabs(a));
212 mn = std::fmin(mn, std::fabs(a));
213 }
214 }
215 if (mx == 0.0)
216 continue;
217 rowsumAbs = std::fmax(rowsumAbs, std::fabs(s));
218 rowsumRelMax = std::fmax(rowsumRelMax, std::fabs(s) / mx);
219 rowsumRelMin = std::fmax(rowsumRelMin, std::fabs(s) / mn);
220 }
221
222 // --- skew, printed here for a quick read (the spectrum is Python's job) ------------------------
223 double fs = 0, fa = 0;
224 for (long r = 0; r < n; ++r)
225 for (long c = 0; c < n; ++c) {
226 const double m = M[(size_t)r * (size_t)n + (size_t)c],
227 t = M[(size_t)c * (size_t)n + (size_t)r];
228 fa += m * m;
229 fs += (m - t) * (m - t);
230 }
231 const double skew = std::sqrt(fs) / std::sqrt(fa + 1e-300);
232
233#ifdef PECLET_FLOW_OPERATOR_DOUBLE
234 const char* prec = cfg.fp32 ? "vf32" : "double"; // vf32: the FP32 V-cycle on the double operator
235#else
236 const char* prec = cfg.fp32 ? "vf32float" : "float";
237#endif
238 std::printf(
239 "%-8s %-8s ratio %-9.3g skew %.4e A*1 defect: abs %.3e /max|a| %.3e /min|a| %.3e\n",
240 prec, geomName(cfg.geom), cfg.ratio, skew, rowsumAbs, rowsumRelMax, rowsumRelMin);
241 std::fflush(stdout);
242
243 if (!outdir.empty()) {
244 char tag[256];
245 std::snprintf(tag, sizeof(tag), "%s/M_%s_%s_n%d_L%d_r%.0e.bin", outdir.c_str(), prec,
246 geomName(cfg.geom), cfg.n, cfg.levels, cfg.ratio);
247 writeMatrix(tag, M, n);
248 std::snprintf(tag, sizeof(tag), "%s/A_%s_%s_n%d_L%d_r%.0e.bin", outdir.c_str(), prec,
249 geomName(cfg.geom), cfg.n, cfg.levels, cfg.ratio);
250 writeMatrix(tag, A, n);
251 }
252}
253
254} // namespace
255
256int main(int argc, char** argv) {
257 Config cfg;
258 std::string outdir;
259 bool sweep = false;
260 for (int i = 1; i < argc; ++i) {
261 const std::string a = argv[i];
262 auto next = [&]() { return (i + 1 < argc) ? argv[++i] : (char*)"0"; };
263 if (a == "--n")
264 cfg.n = std::atoi(next());
265 else if (a == "--levels")
266 cfg.levels = std::atoi(next());
267 else if (a == "--geom")
268 cfg.geom = std::strcmp(next(), "periodic") == 0 ? 0 : 1;
269 else if (a == "--ratio")
270 cfg.ratio = std::atof(next());
271 else if (a == "--outdir")
272 outdir = next();
273 else if (a == "--sweep")
274 sweep = true;
275 else if (a == "--precision")
276 cfg.fp32 = std::strcmp(next(), "fp32") == 0;
277 }
278 Kokkos::initialize(argc, argv);
279 {
280 if (sweep) {
281 const double ratios[] = {1.0, 1e2, 1e3, 1e4, 1e5, 1e6};
282 for (int g = 0; g < 2; ++g)
283 for (double r : ratios) {
284 Config c = cfg;
285 c.geom = g;
286 c.ratio = r;
287 run(c, outdir);
288 }
289 } else {
290 run(cfg, outdir);
291 }
292 }
293 Kokkos::finalize();
294 return 0;
295}
void removeMean(Level &lv, CCField f, bool stopGuard=false)
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})
void precondVcycleFp32(CCField zz, CCField rr, int e, int k, CCField p)
void matvecOverlap(Level &l0, CCField y, CCField v)
void vcycle(int L, bool sym)
const char * fp32VcycleIneligible(bool krylov) const
void setOpenness(CCConst ox, CCConst oy, CCConst oz, double idx2, double idy2, double idz2)
Level & level(int L)
void setBoundaryConditions(const int bc[6])
double maxabs(Level &lv, CCField a)
static constexpr int G
void init(int nx, int ny, int nz, int nLevels)
void setVcyclePrecision(int mode)
flow — portable (Kokkos) geometric multigrid for the cut-cell (variable-openness) pressure Poisson.
y
Definition cmp.py:24
M
Definition conj.py:180
Kokkos::View< const double *, CCMem > CCConst
Kokkos::View< double *, CCMem > CCField
dict A
Definition post.py:33
int m
Definition post.py:35
hdr
Definition post.py:17
t
Definition post.py:21
Definition sweep.py:1
int y
int x
Kokkos::View< const double *, CCMem > CCConst
Kokkos::View< double *, CCMem > CCField
static constexpr int G
static int run(int bc)