Skip to content

Commit d086e7a

Browse files
committed
Make common global ownership stage-independent
1 parent 6f7bf44 commit d086e7a

6 files changed

Lines changed: 141 additions & 76 deletions

File tree

src/common/m_global_parameters_common.fpp

Lines changed: 4 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -27,20 +27,6 @@ module m_global_parameters_common
2727
! num_dims, num_vels, weno_polyn, muscl_polyn, weno_num_stencils, wenojs, igr, etc.
2828
#:include 'generated_case_opt_decls.fpp'
2929

30-
! For pre_process and post_process: num_dims and num_vels are declared manually here
31-
! (sim gets them from generated_case_opt_decls.fpp above)
32-
#ifndef MFC_SIMULATION
33-
integer :: num_dims !< Number of spatial dimensions
34-
integer :: num_vels !< Number of velocity components (different from num_dims for mhd)
35-
#endif
36-
37-
! For pre_process: weno_polyn and muscl_polyn are declared manually here
38-
! (sim gets them from generated_case_opt_decls.fpp; post does not use them)
39-
#ifdef MFC_PRE_PROCESS
40-
integer :: weno_polyn !< Degree of the WENO polynomials
41-
integer :: muscl_polyn !< Degree of the MUSCL polynomials
42-
#endif
43-
4430
!> @name Annotations of the structure of the state and flux vectors in terms of the size and configuration of the system of
4531
!! equations
4632
!> @{
@@ -90,49 +76,9 @@ module m_global_parameters_common
9076
!> Minimum cell widths. These are distinct from the per-cell width arrays named dx, dy, and dz in simulation and post-process.
9177
real(wp) :: dx_min, dy_min, dz_min
9278

93-
#ifdef MFC_SIMULATION
9479
$:GPU_DECLARE(create='[sys_size, eqn_idx, b_size, tensor_size]')
9580
$:GPU_DECLARE(create='[shear_num, shear_indices, shear_BC_flip_num, shear_BC_flip_indices]')
96-
! Device residency for namelist/case-opt state declared above via the generated
97-
! includes: declare directives must live in the declaring module (Cray ftn rejects
98-
! declare-target on use-associated names), so these moved here from simulation.
99-
$:GPU_DECLARE(create='[cyl_coord]')
100-
$:GPU_DECLARE(create='[dt, m, n, p]')
101-
$:GPU_DECLARE(create='[cfl_target]')
102-
$:GPU_DECLARE(create='[int_comp, ic_eps, ic_beta]')
103-
$:GPU_DECLARE(create='[muscl_eps]')
104-
$:GPU_DECLARE(create='[mpp_lim, model_eqns, mixture_err, alt_soundspeed]')
105-
$:GPU_DECLARE(create='[avg_state, mp_weno, weno_eps, teno_CT, hypoelasticity]')
106-
$:GPU_DECLARE(create='[hyperelasticity, elasticity, low_Mach]')
107-
$:GPU_DECLARE(create='[cont_damage, hyper_cleaning]')
108-
$:GPU_DECLARE(create='[relax, relax_model, palpha_eps, ptgalpha_eps]')
109-
$:GPU_DECLARE(create='[down_sample]')
110-
$:GPU_DECLARE(create='[fd_order]')
111-
$:GPU_DECLARE(create='[rhoref, pref]')
112-
$:GPU_DECLARE(create='[ib, num_ibs]')
113-
$:GPU_DECLARE(create='[ib_coefficient_of_friction]')
114-
$:GPU_DECLARE(create='[Ca, Web, Re_inv]')
115-
$:GPU_DECLARE(create='[bubbles_euler, polytropic, polydisperse]')
116-
$:GPU_DECLARE(create='[adv_n, adap_dt, adap_dt_tol, adap_dt_max_iters]')
117-
$:GPU_DECLARE(create='[bubble_model, thermal]')
118-
$:GPU_DECLARE(create='[poly_sigma]')
119-
$:GPU_DECLARE(create='[qbmm, pi_fac]')
120-
$:GPU_DECLARE(create='[R0ref]')
121-
$:GPU_DECLARE(create='[acoustic_source, num_source]')
122-
$:GPU_DECLARE(create='[sigma, surface_tension]')
123-
$:GPU_DECLARE(create='[bubbles_lagrange]')
124-
$:GPU_DECLARE(create='[Bx0]')
125-
$:GPU_DECLARE(create='[tau_star, cont_damage_s, alpha_bar]')
126-
$:GPU_DECLARE(create='[hyper_cleaning_speed, hyper_cleaning_tau]')
127-
$:GPU_DECLARE(create='[synthetic_turbulence, num_turbulent_sources, synth_U_inf]')
128-
#:if not MFC_CASE_OPTIMIZATION
129-
$:GPU_DECLARE(create='[num_dims, num_vels, weno_polyn, weno_order]')
130-
$:GPU_DECLARE(create='[weno_num_stencils, num_fluids, wenojs]')
131-
$:GPU_DECLARE(create='[mapped_weno, wenoz, teno, wenoz_q, mhd, relativity]')
132-
$:GPU_DECLARE(create='[igr_iter_solver, igr_order, viscous, igr_pres_lim, igr]')
133-
$:GPU_DECLARE(create='[recon_type, muscl_order, muscl_polyn, muscl_lim]')
134-
#:endif
135-
#endif
81+
$:GPU_DECLARE(create='[elasticity]')
13682

13783
!> @name Processor coordinates and parallel-IO addressing (identical declaration across all three targets)
13884
!> @{
@@ -163,10 +109,11 @@ contains
163109
!! - qbmm_idx allocations and fills (diverge between pre vs sim/post)
164110
!! - sim-only: gam = bub_pp%gam_g, nmomsp/nmomtot, Re_idx allocation, GPU_UPDATE calls
165111
!! - post-only: beta_idx increment (bubbles_lagrange path), offset/grid allocations
166-
impure subroutine s_initialize_eqn_idx(nmom_in, nb_in)
112+
impure subroutine s_initialize_eqn_idx(nmom_in, nb_in, six_eqn_alf_is_advected)
167113

168114
integer, intent(in) :: nmom_in
169115
integer, intent(in) :: nb_in
116+
logical, intent(in) :: six_eqn_alf_is_advected
170117

171118
! Gamma/Pi_inf Model
172119

@@ -252,9 +199,7 @@ contains
252199
eqn_idx%E = eqn_idx%mom%end + 1
253200
eqn_idx%adv%beg = eqn_idx%E + 1
254201
eqn_idx%adv%end = eqn_idx%E + num_fluids
255-
#ifdef MFC_SIMULATION
256-
eqn_idx%alf = eqn_idx%adv%end
257-
#endif
202+
if (six_eqn_alf_is_advected) eqn_idx%alf = eqn_idx%adv%end
258203
eqn_idx%int_en%beg = eqn_idx%adv%end + 1
259204
eqn_idx%int_en%end = eqn_idx%adv%end + num_fluids
260205
sys_size = eqn_idx%int_en%end
@@ -352,7 +297,6 @@ contains
352297
integer :: ierr !< Generic flag used to identify and report MPI errors
353298
#endif
354299

355-
#ifdef MFC_SIMULATION
356300
! Under case-optimization, num_dims and num_vels are compile-time parameters; skip assignment.
357301
#:if not MFC_CASE_OPTIMIZATION
358302
num_dims = 1 + min(1, n) + min(1, p)
@@ -363,15 +307,6 @@ contains
363307
num_vels = num_dims
364308
end if
365309
#:endif
366-
#else
367-
num_dims = 1 + min(1, n) + min(1, p)
368-
369-
if (mhd) then
370-
num_vels = 3
371-
else
372-
num_vels = num_dims
373-
end if
374-
#endif
375310

376311
allocate (proc_coords(1:num_dims))
377312

src/post_process/m_global_parameters.fpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -326,7 +326,7 @@ contains
326326
if (model_eqns == model_eqns_5eq .and. qbmm) nmom = 6
327327

328328
! Populate eqn_idx, sys_size, b_size, tensor_size, elasticity, shear_* (shared logic)
329-
call s_initialize_eqn_idx(nmom, nb)
329+
call s_initialize_eqn_idx(nmom, nb, six_eqn_alf_is_advected=.false.)
330330

331331
! post-only: 6eq alf is a dummy (no void fraction in 6eq)
332332
if (model_eqns == model_eqns_6eq) eqn_idx%alf = 1

src/pre_process/m_global_parameters.fpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -447,7 +447,7 @@ contains
447447
if (model_eqns == model_eqns_5eq .and. bubbles_euler .and. qbmm .and. nnode == 4) nmom = 6
448448

449449
! Populate eqn_idx, sys_size, b_size, tensor_size, elasticity, shear_* (shared logic)
450-
call s_initialize_eqn_idx(nmom, nb)
450+
call s_initialize_eqn_idx(nmom, nb, six_eqn_alf_is_advected=.false.)
451451

452452
! Per-target (pre_process): qbmm_idx allocations and fills
453453
if (model_eqns == model_eqns_5eq .and. bubbles_euler) then

src/simulation/m_global_parameters.fpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -708,7 +708,7 @@ contains
708708
Re_size_max = 0
709709
710710
! Populate eqn_idx, sys_size, b_size, tensor_size, elasticity, shear_* (shared logic)
711-
call s_initialize_eqn_idx(nmom, nb)
711+
call s_initialize_eqn_idx(nmom, nb, six_eqn_alf_is_advected=.true.)
712712
713713
! sim-only: GPU update for shear state after s_initialize_eqn_idx populated it
714714
if (model_eqns == model_eqns_5eq .or. model_eqns == model_eqns_6eq) then

toolchain/mfc/params/generators/fortran_gen.py

Lines changed: 115 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,97 @@
2828

2929
_VALID_TARGETS = ("pre", "sim", "post")
3030

31+
# Scalar simulation parameters whose generated declarations own device storage.
32+
# Case-optimization parameters are emitted by generated_case_opt_decls.fpp; all
33+
# other names are emitted by generated_decls.fpp.
34+
SIM_GPU_DECL_VARS = {
35+
"Bx0",
36+
"Ca",
37+
"R0ref",
38+
"Re_inv",
39+
"Web",
40+
"acoustic_source",
41+
"adap_dt",
42+
"adap_dt_max_iters",
43+
"adap_dt_tol",
44+
"adv_n",
45+
"alpha_bar",
46+
"alt_soundspeed",
47+
"avg_state",
48+
"bubble_model",
49+
"bubbles_euler",
50+
"bubbles_lagrange",
51+
"cfl_target",
52+
"cont_damage",
53+
"cont_damage_s",
54+
"cyl_coord",
55+
"down_sample",
56+
"dt",
57+
"fd_order",
58+
"hyper_cleaning",
59+
"hyper_cleaning_speed",
60+
"hyper_cleaning_tau",
61+
"hyperelasticity",
62+
"hypoelasticity",
63+
"ib",
64+
"ib_coefficient_of_friction",
65+
"ic_beta",
66+
"ic_eps",
67+
"igr",
68+
"igr_iter_solver",
69+
"igr_order",
70+
"igr_pres_lim",
71+
"int_comp",
72+
"low_Mach",
73+
"m",
74+
"mapped_weno",
75+
"mixture_err",
76+
"model_eqns",
77+
"mp_weno",
78+
"mpp_lim",
79+
"muscl_eps",
80+
"muscl_lim",
81+
"muscl_order",
82+
"muscl_polyn",
83+
"n",
84+
"num_dims",
85+
"num_fluids",
86+
"num_ibs",
87+
"num_source",
88+
"num_turbulent_sources",
89+
"num_vels",
90+
"p",
91+
"palpha_eps",
92+
"pi_fac",
93+
"poly_sigma",
94+
"polydisperse",
95+
"polytropic",
96+
"pref",
97+
"ptgalpha_eps",
98+
"qbmm",
99+
"recon_type",
100+
"relativity",
101+
"relax",
102+
"relax_model",
103+
"rhoref",
104+
"sigma",
105+
"surface_tension",
106+
"synth_U_inf",
107+
"synthetic_turbulence",
108+
"tau_star",
109+
"teno",
110+
"teno_CT",
111+
"thermal",
112+
"viscous",
113+
"weno_eps",
114+
"weno_num_stencils",
115+
"weno_order",
116+
"weno_polyn",
117+
"wenojs",
118+
"wenoz",
119+
"wenoz_q",
120+
}
121+
31122

32123
def _check_target(target: str) -> None:
33124
if target not in _VALID_TARGETS:
@@ -117,6 +208,7 @@ def generate_decls_fpp(target: str) -> str:
117208
"""Return Fortran declarations (scalars + known arrays) for a target."""
118209
_check_target(target)
119210
lines = [_HEADER.rstrip()]
211+
declared_names = set()
120212
for name in _decl_vars_for_target(target):
121213
if not _is_simple_scalar(name):
122214
continue
@@ -132,13 +224,15 @@ def generate_decls_fpp(target: str) -> str:
132224
ftype = fortran_type_decl(member)
133225
dim = FORTRAN_ARRAY_DIMS[name]
134226
lines.append(f"{(ftype + ', dimension(' + dim + ')').ljust(_ARRAY_DECL_COL)}:: {name}")
227+
declared_names.add(name)
135228
continue
136229
param = REGISTRY.all_params.get(name)
137230
if param is None:
138231
continue
139232
if any(k.startswith(f"{name}(") for k in REGISTRY.all_params):
140233
raise ValueError(f"{name!r} has indexed variants (e.g. {name}(1)) but is missing from " "FORTRAN_ARRAY_DIMS. Add it there with its Fortran dimension expression.")
141234
lines.append(f"{fortran_type_decl(param).ljust(_DECL_COL)}:: {name}")
235+
declared_names.add(name)
142236
for name, (ftype, dim, gpu, desc) in TYPED_DECLS.items():
143237
if name not in NAMELIST_VARS or target not in NAMELIST_VARS[name]:
144238
continue
@@ -148,8 +242,12 @@ def generate_decls_fpp(target: str) -> str:
148242
padded += " "
149243
doc = f" !< {desc}" if desc else ""
150244
lines.append(f"{padded}:: {name}{doc}")
245+
declared_names.add(name)
151246
if gpu and target == "sim":
152247
lines.append(f"$:GPU_DECLARE(create='[{name}]')")
248+
if target == "sim":
249+
for name in sorted(SIM_GPU_DECL_VARS & declared_names):
250+
lines.append(f"$:GPU_DECLARE(create='[{name}]')")
153251
return "\n".join(lines) + "\n"
154252

155253

@@ -179,6 +277,7 @@ def generate_constants_fpp() -> str:
179277
("weno_num_stencils", "integer", "Number of stencils for WENO reconstruction"),
180278
("wenojs", "logical", "WENO-JS (default)"),
181279
]
280+
COMMON_CASE_OPT_EXTRA_NAMES = {"num_dims", "num_vels", "weno_polyn", "muscl_polyn"}
182281

183282
_CASE_OPT_DECL_COL = 24 # '::' alignment for case-opt declarations
184283

@@ -227,6 +326,10 @@ def generate_case_opt_decls_fpp() -> str:
227326
if_lines.append(f" {ftype}, parameter :: {name} = ${{{name}}}$ !< {desc}")
228327
else_lines.append(f" {ftype.ljust(_CASE_OPT_DECL_COL)}:: {name}")
229328

329+
declared_names = {name for name, _, _ in CASE_OPT_EXTRA_LINES} | set(params_to_emit)
330+
for name in sorted(SIM_GPU_DECL_VARS & declared_names):
331+
else_lines.append(f" $:GPU_DECLARE(create='[{name}]')")
332+
230333
parts = [_HEADER.rstrip(), "#:if MFC_CASE_OPTIMIZATION"]
231334
parts.extend(if_lines)
232335
parts.append("#:else")
@@ -235,6 +338,15 @@ def generate_case_opt_decls_fpp() -> str:
235338
return "\n".join(parts) + "\n"
236339

237340

341+
def generate_common_extra_decls_fpp() -> str:
342+
"""Return computed-scalar declarations needed by common pre/post code."""
343+
lines = [_HEADER.rstrip()]
344+
for name, ftype, _ in CASE_OPT_EXTRA_LINES:
345+
if name in COMMON_CASE_OPT_EXTRA_NAMES:
346+
lines.append(f"{ftype.ljust(_CASE_OPT_DECL_COL)}:: {name}")
347+
return "\n".join(lines) + "\n"
348+
349+
238350
# Struct roots in NAMELIST_VARS whose member-level broadcasts are irregular
239351
# (per-target member subsets, grouped array members, nested loops, etc.).
240352
# These are kept in the manual residue of m_mpi_proxy.fpp.
@@ -572,9 +684,8 @@ def get_generated_files(build_dir: Path) -> List[Tuple[Path, str]]:
572684
573685
Paths match the cmake include directory structure:
574686
build_dir/include/{full_target}/generated_{namelist,decls,constants,case_opt_decls,bcast}.fpp
575-
Every target gets generated_case_opt_decls.fpp: real content for simulation,
576-
a header-only stub for the others (Fypp resolves #:include at parse time, so
577-
the file must exist for every target even inside a dead conditional).
687+
Every target gets generated_case_opt_decls.fpp: the full case-optimization
688+
block for simulation and common computed-scalar declarations for pre/post.
578689
Every target gets generated_bcast.fpp with its MPI broadcast statements.
579690
"""
580691
result = []
@@ -585,7 +696,7 @@ def get_generated_files(build_dir: Path) -> List[Tuple[Path, str]]:
585696
result.append((inc / "generated_constants.fpp", generate_constants_fpp()))
586697
for short, full in TARGETS:
587698
inc = build_dir / "include" / full
588-
content = generate_case_opt_decls_fpp() if short == "sim" else _HEADER + "! (no case-optimization declarations for this target)\n"
699+
content = generate_case_opt_decls_fpp() if short == "sim" else generate_common_extra_decls_fpp()
589700
result.append((inc / "generated_case_opt_decls.fpp", content))
590701
for short, full in TARGETS:
591702
inc = build_dir / "include" / full

toolchain/mfc/params_tests/test_fortran_gen.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -323,6 +323,25 @@ def test_generate_case_opt_decls_fpp():
323323
assert "AUTO-GENERATED" in out
324324

325325

326+
def test_common_computed_scalars_are_declared_for_every_target():
327+
from pathlib import Path
328+
329+
from mfc.params.generators.fortran_gen import get_generated_files
330+
331+
files = {path.parent.name: content for path, content in get_generated_files(Path("/build")) if path.name == "generated_case_opt_decls.fpp"}
332+
for target in ("pre_process", "simulation", "post_process"):
333+
for name in ("num_dims", "num_vels", "weno_polyn", "muscl_polyn"):
334+
assert f":: {name}" in files[target]
335+
336+
337+
def test_simulation_generated_scalars_own_gpu_declarations():
338+
from mfc.params.generators.fortran_gen import SIM_GPU_DECL_VARS, generate_case_opt_decls_fpp, generate_decls_fpp
339+
340+
generated = generate_decls_fpp("sim") + generate_case_opt_decls_fpp()
341+
for name in SIM_GPU_DECL_VARS:
342+
assert generated.count(f"$:GPU_DECLARE(create='[{name}]')") == 1
343+
344+
326345
# ── generate_bcast_fpp tests ──────────────────────────────────────────────────
327346

328347

0 commit comments

Comments
 (0)