flow 1.4.0
Kokkos cut-cell IBM incompressible Navier-Stokes solver + pnm pore extraction
Loading...
Searching...
No Matches
weak_swarm.py
Go to the documentation of this file.
1#!/usr/bin/env python3
2"""Multi-GPU WEAK scaling of a periodic swarm of deformable bubbles (block VoF, momentum advection
3on, the case-A groups): a fixed box of cells per rank, tiled along x, then y, then z.
4
5 PYTHONPATH=<PECLET_FLOW_MPI build> \\
6 srun --mpi=pmix --ntasks=P --gpus-per-task=1 --gpu-bind=per_task:1 \\
7 python tests/study/vof_perf/weak_swarm.py N [--warm W] [--cells n] [--d-over-h D]
8 [--bubbles-per-axis B] [--rtol R] [--levels L] [--comm-avoiding MODE] [--single]
9 [--out FILE.json] [--tag T]
10
11The case is case A of the bubble-swarm validation (tests/study/case_a on branch case-a: Ar 29.9,
12Bo 2, rho_b/rho_l = mu_b/mu_l = 0.1, buoyancy with the mixture weight removed, the volume mean u_x
13held at 0 by set_superficial_velocity) with many bubbles instead of one, in CELL units as
14prof_mpi.py / run_peclet.build() (D = rho_l = g = 1, lengths scaled by S = d/h: mu' = S^2 mu,
15sigma' = S^3 sigma, g' = S g; test_vof_blocks_physical_units.py proves the physical domain equal
16to 1e-12). Gravity along -x, triply periodic, starting at rest.
17
18Per rank: an n^3 box (default 256^3) carrying B^3 bubbles (default 2^3 = 8) of diameter d/h cells
19(default 20) on a lattice of spacing n/B, each centre perturbed by up to +-PERTURB/2 of the free
20gap with the fixed seed SEED. The rank box is tiled (TX, TY, TZ) times, doubling x, then y, then z
21(P = 1, 2, 4, 8, 16, 32 -> (1,1,1), (2,1,1), (2,2,1), (2,2,2), (4,2,2), (4,4,2)); every tile carries
22the SAME perturbed bubble set, so every rank has the same work when the ORB blocks are the tiles.
23
24--levels L sets the pressure multigrid depth (set_pressure_multigrid(True, L), before the geometry);
25without it the solver default (4) is used. At 4 levels a 256^3 box keeps a 32^3-per-rank coarsest
26level, which goes to the host GraphAMG bottom (rebuilt every step under variable density).
27
28--comm-avoiding MODE sets diagnostics.set_comm_avoiding(MODE) ('both' | 'off' | 'momentum' |
29'pressure') before init_mpi; without it the solver default ('both') is used. The modes are
30bit-identical by construction: a measurement of the halo-exchange cost, not of the physics.
31
32At P = 1 the default is the DISTRIBUTED path (init_mpi at size 1, as prof_mpi.py); --single runs the
33single-rank solver instead (no mpi_block/init_mpi, as run_mpi.py), the honest one-GPU reference.
34
35W warm-up steps (default 5), then N timed steps, dt = 0.25 min(CFL, capillary) every step (case A).
36Rank 0 prints one `RESULT key=value ...` line and, with --out, writes the same numbers as JSON:
37ms/step (wall), max-rank step / projection / momentum / predictor / pressure-allreduce ms, pressure
38iterations, cells per rank, the ORB block sizes, setup seconds, and `hash`: SHA-256 over every
39rank's u, v, w, p, C (rank order) plus the timed dt and iteration sequences -- equal hashes at the
40same P are the bit-identity gate across MPI transports (PECLET_CORE_GPU_AWARE_MPI=0/1).
41"""
42import hashlib
43import json
44import os
45import sys
46import time
47
48import numpy as np
49from mpi4py import MPI
50
51A = list(sys.argv)
52
53
54def arg(name, default, cast=str):
55 return cast(A[A.index(name) + 1]) if name in A else default
56
57
58# --- case A groups (tests/study/case_a/run_case_a.py), units D = rho_l = g = 1 ----------------
59AR, BO, RHO_RATIO, MU_RATIO = 29.9, 2.0, 0.1, 0.1
60RHO_L, G, D = 1.0, 1.0, 1.0
61RHO_G = RHO_RATIO * RHO_L
62MU_L = np.sqrt(RHO_L * abs(RHO_G - RHO_L) * G * D ** 3) / AR
63MU_G = MU_RATIO * MU_L
64SIGMA = abs(RHO_G - RHO_L) * G * D ** 2 / BO
65SEED, PERTURB = 20261024, 0.25
66
67N = int(A[1])
68WARM = arg("--warm", 5, int)
69CELLS = arg("--cells", 256, int)
70S = arg("--d-over-h", 20.0, float)
71B = arg("--bubbles-per-axis", 2, int)
72RTOL = arg("--rtol", 1e-8, float)
73LEVELS = arg("--levels", None, int)
74CA = arg("--comm-avoiding", None)
75OUT = arg("--out", None)
76TAG = arg("--tag", "")
77comm = MPI.COMM_WORLD
78rank, size = comm.Get_rank(), comm.Get_size()
79SINGLE = "--single" in A
80if SINGLE and size != 1:
81 sys.exit("--single needs exactly one rank")
82
83
84def tiles(p):
85 """Doubling x, then y, then z: p must be a power of two."""
86 if p & (p - 1):
87 sys.exit(f"weak_swarm: {p} ranks is not a power of two")
88 t = [1, 1, 1]
89 ax = 0
90 while t[0] * t[1] * t[2] < p:
91 t[ax] *= 2
92 ax = (ax + 1) % 3
93 return t
94
95
96TX, TY, TZ = tiles(size)
97NX, NY, NZ = TX * CELLS, TY * CELLS, TZ * CELLS
98
99
101 """One rank box's perturbed B^3 lattice (fixed seed), replicated over every tile; cell units."""
102 rng = np.random.default_rng(SEED)
103 sp = CELLS / B
104 gap = sp - S
105 if gap <= 0:
106 sys.exit(f"weak_swarm: bubbles (d/h {S}) do not fit a lattice spacing of {sp} cells")
107 box = []
108 for k in range(B):
109 for j in range(B):
110 for i in range(B):
111 c = (np.array([i, j, k]) + 0.5) * sp + (rng.random(3) - 0.5) * PERTURB * gap
112 box.append(c)
113 out = []
114 for tz in range(TZ):
115 for ty in range(TY):
116 for tx in range(TX):
117 o = np.array([tx, ty, tz]) * CELLS
118 out += [(float(c[0] + o[0]), float(c[1] + o[1]), float(c[2] + o[2]), 0.5 * S)
119 for c in box]
120 return out
121
122
123t_setup0 = time.perf_counter()
124import peclet.flow as pf # after the argument checks: an import is seconds on a GPU
125
126if SINGLE:
127 org, siz = (0, 0, 0), (NX, NY, NZ)
128else:
129 org, siz = pf.mpi_block(NX, NY, NZ)
130s = pf.Solver(*siz)
131if CA is not None:
132 s.diagnostics.set_comm_avoiding(CA) # before init_mpi: the momentum half is latched there
133if not SINGLE:
134 s.init_mpi(NX, NY, NZ)
135if LEVELS is not None:
136 s.set_pressure_multigrid(True, LEVELS) # before the geometry builds the hierarchy
137s.set_rho(RHO_L)
138s.set_mu(S * S * MU_L)
139s.set_pressure_geometry(np.full(tuple(siz), 10.0, order="F")) # all fluid (SDF > 0)
140s.enable_vof()
141s.set_vof(np.zeros(tuple(siz), order="F"))
142# C = 1 is GAS (the block container's union starts empty)
143s.set_property_model("rho", "linear", "C", [RHO_L, RHO_G - RHO_L])
144s.set_property_model("mu", "linear", "C", [S * S * MU_L, S * S * (MU_G - MU_L)])
145s.set_surface_tension(S ** 3 * SIGMA)
147s.enable_vof_blocks(seeds)
148s.enable_vof_block_csf()
149vol = comm.allreduce(sum(b["volume"] for b in s.diagnostics.vof_block_stats()), op=MPI.SUM)
150alpha = vol / (NX * NY * NZ)
151rho_av = RHO_L + (RHO_G - RHO_L) * alpha
152# gravity along -x with the mixture weight removed: f_x = -(rho(C) - <rho>) g (case A)
153s.set_property_model("force_x", "linear", "C",
154 [-S * (RHO_L - rho_av) * G, -S * (RHO_G - RHO_L) * G])
155s.set_superficial_velocity(True, "x", 0.0)
156s.set_pressure_pcg(True, 800, RTOL) # last (the rho closure re-selects); case A's driver
157s.update_properties() # so the first capillary_dt sees rho(C)
158comm.Barrier()
159t_setup = comm.allreduce(time.perf_counter() - t_setup0, op=MPI.MAX)
160
161dts, iters, rows = [], [], []
162KEYS = ("step", "projection", "momentum", "predictor", "pressure_allreduce")
163
164
165def one(timed):
166 lim = s.vof_step_limits()
167 dt = 0.25 * min(lim["cfl_dt"], lim["capillary_dt"])
168 s.set_dt(dt)
169 t0 = time.perf_counter()
170 s.step()
171 t1 = time.perf_counter()
172 if timed:
173 tm = s.diagnostics.last_step_timers()
174 dts.append(dt)
175 iters.append(s.diagnostics.last_pressure_iterations())
176 rows.append([t1 - t0] + [float(tm[k]) for k in KEYS])
177
178
179for _ in range(WARM):
180 one(False)
181comm.Barrier()
182if rank == 0:
183 print("[weak_swarm] timed steps begin", file=sys.stderr, flush=True)
184w0 = time.perf_counter()
185for _ in range(N):
186 one(True)
187comm.Barrier()
188wall = time.perf_counter() - w0
189
190# per-step maxima over ranks (the slowest rank sets the step), then means over the timed steps
191R = np.asarray(rows)
192Rmax = np.empty_like(R)
193comm.Allreduce(R, Rmax, op=MPI.MAX)
194mean_ms = 1000.0 * Rmax.mean(axis=0)
195
196h = hashlib.sha256()
197for f in (s.get_u, s.get_v, s.get_w, lambda: s.get_field("p"), lambda: s.get_field("C")):
198 h.update(np.ascontiguousarray(f()).tobytes())
199digests = comm.gather(h.hexdigest(), root=0)
200blocks = comm.gather("x".join(map(str, siz)), root=0)
201if rank == 0:
202 g = hashlib.sha256()
203 for d in digests:
204 g.update(d.encode())
205 g.update(np.asarray(dts).tobytes())
206 g.update(np.asarray(iters, dtype=np.int64).tobytes())
207 ub = sorted(set(blocks))
208 res = {
209 "tag": TAG, "np": size, "path": "single" if SINGLE else "distributed",
210 "gpu_aware_env": os.environ.get("PECLET_CORE_GPU_AWARE_MPI", "unset"),
211 "flow_module": os.path.dirname(pf.__file__), "space": str(getattr(pf, "execution_space", "?")),
212 "grid": [NX, NY, NZ], "tiles": [TX, TY, TZ], "cells_per_rank": CELLS ** 3,
213 "blocks": ub, "d_over_h": S, "bubbles": len(seeds), "alpha": alpha, "rtol": RTOL,
214 "levels": LEVELS if LEVELS is not None else "default",
215 "comm_avoiding": s.diagnostics.comm_avoiding,
216 "warm": WARM, "steps": N, "setup_s": t_setup, "wall_ms": 1000.0 * wall / N,
217 "step_ms": float(mean_ms[0]), "timer_step_ms": float(mean_ms[1]),
218 "proj_ms": float(mean_ms[2]), "momentum_ms": float(mean_ms[3]),
219 "predictor_ms": float(mean_ms[4]), "allreduce_ms": float(mean_ms[5]),
220 "proj_frac": float(mean_ms[2] / mean_ms[0]),
221 "iters_mean": float(np.mean(iters)), "iters_min": int(min(iters)),
222 "iters_max": int(max(iters)), "dt_first": dts[0], "dt_last": dts[-1],
223 "hash": g.hexdigest(),
224 }
225 def fmt(v):
226 if isinstance(v, float):
227 return f"{v:.6g}"
228 return ",".join(map(str, v)) if isinstance(v, list) else str(v)
229 print("RESULT " + " ".join(f"{k}={fmt(v)}" for k, v in res.items() if k != "flow_module"),
230 flush=True)
231 if OUT:
232 with open(OUT, "w") as fo:
233 json.dump(res, fo, indent=1)
arg(name, default, cast=str)
Definition weak_swarm.py:54
one(timed)