Kokkos and C++: I saw an example using Kokkos::ScopeGuard instead of…
- User
Kokkos and C++: I saw an example using Kokkos::ScopeGuard instead of initialize/finalize. Is this just syntactic sugar, or should we really use this? Wouldn't that potentially collide with MPI finalize?
- Assistant
It’s more than syntactic sugar. Kokkos::ScopeGuard is the RAII wrapper around Kokkos::initialize/finalize that makes the lifecycle exception-safe and easier to reason about (especially in the presence of early returns or throws) and plays nicely when libraries may or may not initialize Kokkos themselves. It only calls finalize if it actually performed the initialize, so nested guards are safe.
MPI interaction
- No collision as long as you keep the usual ordering:
- MPI_Init (or MPI_Init_thread)
- Kokkos initialize
- your work
- Kokkos finalize
- MPI_Finalize
With ScopeGuard, just use a scope to enforce that order:
int main(int argc, char* argv[]) { MPI_Init(&argc, &argv); { Kokkos::ScopeGuard guard(argc, argv); // or guard(Kokkos::InitializationSettings{...}); // Kokkos + MPI work here } // guard goes out of scope → Kokkos::finalize() happens here MPI_Finalize(); return 0; }Why prefer ScopeGuard
- Guarantees finalize on all normal code paths (including exceptions/early returns).
- Avoids double-finalize and handles “already-initialized” cases cleanly in libraries.
- Lets you pass argc/argv or settings, so you still get all the CLI/config benefits.
Gotchas to avoid
- Don’t let the guard outlive MPI (i.e., don’t place it at static/global scope if you call MPI_Finalize in main).
- Destructors don’t run on std::exit/abort, so don’t use those if you rely on RAII for teardown.
- Make sure any objects that use Kokkos resources are destroyed before finalize (keep them inside the same scope as the guard).
Bottom line: Use Kokkos::ScopeGuard in C++ apps. It’s the idiomatic, safer pattern, and it won’t conflict with MPI as long as you scope it so Kokkos finalizes before MPI_Finalize.
- No collision as long as you keep the usual ordering:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.