Skip to content

Phonon_BvK_PG: OpenACC port (component + eigen solver), drop NOACC - #3002

Draft
willend wants to merge 58 commits into
mainfrom
2026-11-bvk-openacc
Draft

willend wants to merge 58 commits into
mainfrom
2026-11-bvk-openacc

Conversation

@willend

@willend willend commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

Depends on #2344. This branch is built on top of the head of that draft (lefmann/McCode main, bd2d044). Rebase or merge it after #2344 lands. Until then the diff here also contains #2344's commits. The changes themselves are the last two commits, b49a15d and 3a6b482.

Update: c399016 merges #2344's fix commits 2238aae, 6757727 and 266fc1d. The component is taken from #2344, with this port re-applied on top: no NOACC, the acc routine pragmas, the device globals, one root finder without the function pointer, CPU-only error paths (including the one-time BVK_MAX_ROOTS warning) and the double sqrt3. eigen.c keeps this PR's stack arrays, so #2344's free() calls are dropped, and it gains #2344's #undef block. EIGEN_CHECK_N now exits with exit(-1). Check: Test_Phonon_BvK_PG -n 1e5 --seed=1 for 5 parameter sets (default, phononmode=3, phononmode=12, phononmode=7 l=2.5 E=8, E_steps_low=1 E_steps_high=1 phononmode=2). Every monitor is bit-identical to #2344's head 266fc1d (macOS arm64, clang). The -DOPENACC syntax check of the generated C is clean. Still not run on a GPU.

Update 2: a21211e merges #2344's head 4b15258. That brings the Sept 27 2026 dynamical matrix (separate C/D layer block, unit-cell phases, full-q structure factor), the relative eigen.c convergence tolerance, new parameter defaults and %Test lines that check against the paper draft's values. The port is kept: still no NOACC, the new r_1ucA/C, r_3ucA/C and r_4ucA vectors are added to the acc declare/acc update lists, and the convergence warning stays CPU-only. On the CPU, e_mon_beforeana_zoom is bit-identical to 4b15258 at (0,0,2.2), (0.4,0,6) and (2,0,0) (-n 1e6 --seed=1, macOS arm64, clang). The nvc build job passes. Open questions 3, 4 and 5 below are now resolved.

Follow-up to #2344. It replaces the stop-gap in bd2d044 (pragmas removed, component NOACC) with a real OpenACC port.

What changed

mcstas-comps/share/eigen.c / eigen.h (James Avery Hermitian eigen solver)

  • No more per-call heap allocation. eigensystem_hermitian, QHQ, T_QTQ, reflect_region, apply_reflection and matrix_inplace_multiply used to malloc scratch on every call, many times per neutron. They now use fixed-size stack arrays sized by EIGEN_MAXN. It defaults to 12 and can be overridden with #ifndef. On the CPU, n > EIGEN_MAXN aborts with a message. This also removes the leaks: row, vHA, col and Q_tmp were never freed.
  • memset/memcpy are now plain loops.
  • The non-convergence fprintf is wrapped in #ifndef OPENACC. The TIME_EIGENSYSTEMS call counter and timing are CPU-only (#if TIME_EIGENSYSTEMS && !defined(OPENACC)).
  • #pragma acc routine seq is on every device-path function, on both the prototype and the definition.
  • The complex arithmetic still goes through the mccode-complex-lib wrappers, with no type-punning.
  • D/L in eigensystem_hermitian are sized EIGEN_MAXN+1, because T_QTQ(n) reads Din[n]. That element is unused padding, but with exactly n elements the read was out of bounds, as it already was on the heap before.

mcstas-comps/contrib/Phonon_BvK_PG.comp

  • TRACE no longer writes shared state:
    • The global mode moves into p_call[13] and is read by bvk_omega_q.
    • p_call, eigenvectormode, q and q_x/q_y/q_z move from DECLARE to TRACE locals.
    • Unused DECLARE members are removed: Matrix, i, j, qx, qy, qz.
  • One root finder for CPU and GPU, as in Magnon_bcc (Magnon_bcc: bound root list, clamp root index #2965):
    • bvk_zridd/bvk_findroots no longer take a function pointer.
    • The last_fh/last_x2 globals become bvk_findroots locals passed by pointer.
    • bvk_zridd_gpu/bvk_findroots_gpu are removed. They used a different bracketing, and their high-side upper bound used the wrong range.
    • After the CPU-fatal bvk_fatalerror, bvk_zridd returns UNUSED instead of 0.0. That line is only reachable on the GPU, where the bracket is now dropped instead of adding a v_f = 0 root.
  • Device globals: M, Delta, astar, cstar, r_j13, r_1ucA/C, r_3ucA/C, r_4ucA and Phi1..Phi14 get #pragma acc declare create(...) in SHARE and #pragma acc update device(...) at the end of INITIALIZE.
  • The NaN check in bvk_omega_q (fprintf/abort) is CPU-only.
  • The #pragma acc routine seq lines are back on the SHARE helpers, and NOACC is removed.
  • sqrt3 is now a double literal (3a6b482). It used to have an L suffix, so qk, qh and q_Bragg[1] in TRACE were computed in long double. nvc failed on that with Accelerator restriction: unsupported operation: X87TODP in class_Phonon_BvK_PG_trace.

Numerical behaviour

Changed in the last bits on x86_64 only, because of the sqrt3 fix. b49a15d alone is bit-identical on both arm64 and x86_64.

  • arm64 and MSVC (long double is the same as double): output is bit-identical.
  • x86_64 (80-bit long double): weights change in the last bits. Test_Phonon_BvK_PG --seed=1 -n 1e5, built for x86_64 and run under Rosetta, was checked for the default parameters, phononmode=3, phononmode=12 and phononmode=7 l=2.5 E=8. The per-bin counts are identical, so the trajectories are the same. Integrated intensities agree to about 1e-8 relative, far below the statistical error. A few events with near-zero weight (about 1e-36) change more, probably because the nearest-Bragg-point choice flips on a tie. phononmode=7 stays bit-identical.
  • GPU: the component did not run before (NOACC). It now runs the same code path as the CPU.

What was tested

macOS arm64, clang, mccode-dev micromamba env. Base was bd2d044, new was b49a15d.

  • Test_Phonon_BvK_PG, --seed=1, through mcrun (12 MPI ranks for both base and new), with 8 parameter sets:

    • default
    • phononmode=3
    • phononmode=12
    • phononmode=7 l=2.5 E=8
    • E_steps_low=1 E_steps_high=1 phononmode=2
    • DISP=1 phononmode=5
    • DISP=2 phononmode=1
    • Verbose=2 phononmode=4

    Each set is -n 1e5, except the DISP sets (1e4) and the Verbose set (1e3). Every monitor's data is bit-identical. Only the # Date header differs.

  • Single-process runs (binary run directly), comparing data and stdout exactly, with 4 sets:

    • default at -n 1e5
    • DISP=1
    • DISP=2
    • Verbose=7 phononmode=12: about 195k lines that print every eigen-solver Q matrix and eigenvalue set

    All are bit-identical, data and stdout.

  • Warnings: the generated C compiled with clang -std=c99 -Wall -Wextra gives the same 77 warnings as the base. All of them are pre-existing, and none are new.

  • -DOPENACC syntax check: the generated C was syntax-checked with clang and stub openacc.h/accelmath.h headers, so the #ifndef OPENACC branches are at least well-formed.

Not tested:

  • GPU execution. There is no nvc locally. The ubuntu-24.04.conda.classic.gcc.openmpi.openacc CI job builds Test_Phonon_BvK_PG with nvc (-n0) and passes, but it does not run anything. The ubuntu-24.04.conda.openacc.h100-sim job, which runs on a simulated H100, is the first runtime check. Nobody has run it on a real GPU.
  • Linux/gcc, Windows/MSVC: left to CI.

Open questions

  1. Complex functions on the device. This is not the first non-NOACC component to use mccode-complex-lib. Several McXtrace components call it in TRACE without NOACC: PSD_monitor_coh (cexp), Capillary (cabs, cdiv), Mirror_curved (conj, cmul), Source_genesis13 and Source_simplex (cabs). In McStas, SANSPDBFast includes it but does not call it in TRACE, so this is the first McStas component to use it on the device, and the first to run a complex eigen solver on the device. The device path calls creal, cimag, conj and cabs (eigen.c) and cexp (TRACE), plus the library's inline wrappers, which have no acc routine. The wrappers are now static inline (a33edef), and the nvc build job accepts the device path. Whether the results are right on the device still depends on the H100-sim run.
  2. Device stack size. At its deepest, bvk_omega_q → eigensystem_hermitian uses about 15 KB of stack per thread, mostly 12×12 cdouble matrices. This is not measured yet: -Minfo=accel -gpu=ptxinfo gives the real frame sizes, and NV_ACC_CUDA_STACKSIZE raises the limit if a run overflows. If it needs shrinking, three changes that keep the CPU output bit-identical save about 6.5 KB: mirror Phi_12Dim in place instead of copying it to matrix, do the final Qhat·Q in place one column at a time instead of using Q_tmp, and write Phi_12Dim directly without the 6×6 blocks. Separately, computing eigenvalues only during root finding would save time as well, but changes results in the last bits.
  3. Global state shared between instances. Resolved by Initial commit of Phonon_BvK_PG and test instrument #2344's 6757727. shape and verbose are in DECLARE, and verbose reaches bvk_omega_q through parms[14].
  4. rand01()==1.0 edge. Resolved by Initial commit of Phonon_BvK_PG and test instrument #2344's 2238aae. The mode is now floor(12*rand01()), clamped to 11. The root index is clamped to nf-1, and nf == 0 absorbs (d3793dd).
  5. exit on the device. Resolved. Every exit(-1) that TRACE can reach is now behind #ifndef OPENACC, and on the GPU the illegal-mode path does ABSORB. The remaining exit calls are in INITIALIZE (missing geometry) and in CPU-only helpers.

Refs #2988

🤖 Generated with Claude Code

lefmann and others added 28 commits February 24, 2026 11:56
(Mismatching prototype vs. system-provided sort on macOS)
…appers.

(Work remains, some of the comments need to go back in etc...)
)

Ported from #2968 (review for UB/OpenACC hazards):
- findroots/findroots_gpu wrote into vf_list[20] without a bound check.
  The inserts are now bounded by BVK_MAX_ROOTS (= size of vf_list).
- nf == 0 now ABSORBs (before, it read an unset vf_list[0]), and the index
  is clamped to nf-1 because rand01() may return 1.0.
- SHARE used Phonon_simple's PHONON_SIMPLE guard while defining
  incompatible nbose/fatalerror/omega_q/zridd/findroots, so instruments
  combining it with Phonon_simple or Magnon_bcc could not compile. The
  guard is now PHONON_BVK_PG, and the helpers are prefixed bvk_.
- #define DV became BVK_DV: it clobbered the DECLARE variable DV of
  Phonon_simple, Magnon_bcc and others.
- #define pi removed: it broke components that declare a variable named
  pi. Test_Phonon_BvK_PG relied on the leaked macro and now uses PI.

No numerical change: Test_Phonon_BvK_PG (-n 1e6 --seed=1) is
bit-identical. Phonon_BvK_PG + Phonon_simple + Magnon_bcc now builds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…SHARE

The component is NOACC (its root finder takes a function pointer), so it
runs on the CPU. The routine directives still made nvc build these
helpers, and by implication the James Avery eigen solver they call, for
the device. eigen.c's fprintf then fails to compile:
"NVC++-S-1058-Call to variadic function not supported - fprintf".
CPU output is unchanged (Test_Phonon_BvK_PG bit-identical).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…op NOACC

eigen.c/.h (James Avery Hermitian eigen solver):
- Replace the per-call malloc scratch in eigensystem_hermitian, QHQ,
  T_QTQ, reflect_region, apply_reflection and matrix_inplace_multiply
  with fixed-size stack arrays of EIGEN_MAXN (default 12, overridable).
  On the CPU, n > EIGEN_MAXN aborts with a message. This also removes
  the leaks of the old row/vHA/col/Q_tmp buffers.
- memset/memcpy become plain loops.
- Guard the non-convergence fprintf with #ifndef OPENACC. The
  TIME_EIGENSYSTEMS counter/timing is now CPU-only.
- Mark the device-path functions "#pragma acc routine seq" (prototypes
  and definitions).

Phonon_BvK_PG.comp:
- TRACE no longer writes shared state. The phonon mode moves from a
  SHARE global into p_call[13], read by bvk_omega_q. p_call,
  eigenvectormode, q and q_x/q_y/q_z move from DECLARE into TRACE
  locals; unused DECLARE members (Matrix, i, j, qx, qy, qz) are gone.
- One root finder for CPU and GPU: bvk_zridd/bvk_findroots no longer
  take a function pointer, and the last_fh/last_x2 globals become
  findroots locals passed by pointer. bvk_zridd_gpu and
  bvk_findroots_gpu are removed.
- The globals read on the device (verbose, shape, M, Delta, astar,
  cstar, r_j13, Phi1..Phi14) get "acc declare create" and an
  "acc update device" at the end of INITIALIZE.
- The NaN check in bvk_omega_q (fprintf/abort) is CPU-only.
- Restore "#pragma acc routine seq" on the SHARE helpers and remove
  NOACC.

CPU output is bit-identical to bd2d044: Test_Phonon_BvK_PG, --seed=1,
8 parameter sets on 12 MPI ranks and 4 single-process sets, including
Verbose=7, DISP=1 and DISP=2. GPU execution is not tested.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The sqrt3 macro had an L suffix, so the TRACE lines qk/qh and
q_Bragg[1] (x / sqrt3) were computed in long double. nvc cannot do x87
long double on the device and failed with "Accelerator restriction:
unsupported operation: X87TODP" in class_Phonon_BvK_PG_trace.

Numerical behaviour: on arm64 and MSVC (long double == double) output
is bit-identical. On x86_64 (80-bit long double) weights change in the
last bits: Test_Phonon_BvK_PG --seed=1 -n 1e5, built for x86_64 and
run under Rosetta, has identical counts in every bin and integrated
intensities within ~1e-8 relative. A few near-zero-weight events
change more, probably because the nearest-Bragg-point choice flips on
a tie.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
willend and others added 17 commits November 3, 2026 09:11
…o 'exit')

- nrerror(): guard the body (printf + exit) with #ifndef OPENACC, like
  bvk_fatalerror. The illegal-mode branch in TRACE now ABSORBs after
  nrerror; only the GPU reaches that line, and there it avoids indexing
  eigenvalue/index arrays with an out-of-range mode.
- TRACE "Did not hit sample surface from inside": exit(1) on the CPU,
  ABSORB under OPENACC.

The rest of the device path (TRACE, bvk_omega_q, bvk_zridd,
bvk_findroots, eigen.c) has no exit/abort/fprintf left when
preprocessed with -DOPENACC.

CPU output is bit-identical to cfe4e8a on arm64 and x86_64
(Test_Phonon_BvK_PG --seed=1: defaults, phononmode=3, phononmode=12,
E_steps=1, DISP=1; data and stdout).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- eigen.c: free per-call scratch buffers (memory grew ~10 kB per eigensolve)
- eigen.c: #undef generic macros (G, ROWS, COLS, ...) that broke e.g. Guide_gravity
- Phonon_BvK_PG: random mode via floor(), clamped to 11 (was -1 or 12 at rand01() edges)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- mode/verbose passed to SHARE functions via parms[13..14]; shape/verbose in DECLARE
- zridd bracket cache passed explicitly instead of globals
- per-particle q, p_call, eigenvectormode moved from DECLARE to TRACE
- exit(-1) on missing geometry; MCDISPLAY follows the chosen shape
- use runtime HBAR/MNEUTRON (results change by ~1e-4 relative)
- clamp negative eigenvalues, ABSORB non-finite weights and near-tangent exits
- warn once when roots exceed BVK_MAX_ROOTS
- exit(-1) instead of exit(1)/abort; errors to stderr
- drop always-on ROT120 dump and eigensolver timing output
- comment: rows of Q hold conjugate eigenvectors

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- drop dead code: GPU root-finder variants, unused helpers/arrays, MATRIX_TEST and TEST_MATRICES scaffolding
- call complexexp_qdotr directly
- doc fixes: %L link, spelling
- test instrument: header name, %P docs, drop commented-out components and unused variables
- apply mccode-clangformat

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Component taken from #2344 with the OpenACC port re-applied: no NOACC,
acc routine pragmas, device globals, single root finder without the
function pointer, CPU-only error paths, double sqrt3. eigen.c keeps the
stack arrays (frees dropped) and gains the #undef block.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Plain C99 inline has no external definition, so the link fails with
"undefined reference to cmul" whenever the compiler does not inline a
call (e.g. at -O0, or Phonon_BvK_PG's eigen solver with clang on Ubuntu).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
willend and others added 10 commits November 16, 2026 13:05
Port of the dynamical-matrix update from the Sept 27 2026 version by K. Lefmann:
- in-plane couplings use phases from unit-cell origins (r_1uc, r_3uc, r_4uc)
  instead of atom-to-atom vectors
- the C/D layer gets its own 6x6 block; it was a copy of the A/B block,
  although D is mirrored relative to B in Delta
- the structure factor uses the full q instead of the nearest Bragg point,
  to match the new phases
The Sept 27 equations are kept as comments above the complex-lib versions.

Numerical change: results along (0,0,l) are unchanged; off-axis intensities
shift, e.g. -0.7% at (0.4,0,6) and -19% at (2,0,0) on e_mon_beforeana_zoom.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The tolerance was a fixed 1e4*eps (about 2.2e-12). For eigenvalues around
1.8e3 that is close to roundoff, so QR iteration sometimes stalled just above
it and printed "Cannot converge eigenvalue ...". The tolerance is now
scaled by max(1, max_norm(A)).

Results are unchanged for the Test_Phonon_BvK_PG case checked
(1e7 rays, seed 1000, MPI); its 2 warnings are gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Brings in the Sept 27 2026 dynamical matrix (separate C/D block, unit-cell
phases, full-q structure factor), the relative eigen.c tolerance, new
parameter defaults and the %Test lines. OpenACC port kept: no NOACC, the
new r_1uc/r_3uc/r_4uc vectors are added to the acc declare/update lists,
and the eigen.c warning stays CPU-only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@willend

willend commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor Author

Emulated GPU run under way at https://github.com/mccode-dev/McCode/actions/runs/43924317757/job/133499614875 (killed by timeout)

@willend

willend commented Nov 16, 2026

Copy link
Copy Markdown
Contributor Author

The code seems to run - but is quite slow / likely hampered by the big stack requirement for the 12x12's...

Will likely just leave this draft PR for potential later investigation

Copying instruments to: ./mcstas-3.99.99_openacc_mpi_x_8_Phonon_BvK_PG_1e7_Linux_20261116_2131_29

Compiling instruments [seconds]...
Test_Phonon_BvK_PG : 185.99

Running tests / getting status...
Test_Phonon_BvK_PG  :   Display OK (3s)
Test_Phonon_BvK_PG  :  94.96    [val: 2.32306e-10 / 2.28e-10 = 102 %]
 - Test 1 plots generated OK
Test_Phonon_BvK_PG_2:  78.31    [val: 2.0631e-13 / 2e-13 = 103 %]
 - Test 2 plots generated OK
Test_Phonon_BvK_PG_3:  92.38    [val: 2.37192e-10 / 2.43e-10 = 98 %]
 - Test 3 plots generated OK
Test_Phonon_BvK_PG_4:  95.09    [val: 1.3448e-09 / 1.301e-09 = 103 %]
 - Test 4 plots generated OK
(crash or interruption...)
....

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

⌂ Proxy