core 1.8.1
Shared MPI block decomposition, asynchronous ghost-layer exchange, SDF geometry, load balancing (header-only C++20)
Loading...
Searching...
No Matches
grid_halo.hpp
Go to the documentation of this file.
1// core — portable (Kokkos) GPU-resident ghost-layer exchange.
2//
3// Portable (Kokkos) GPU-resident grid halo: the field lives on the device as a
4// peclet::core::View<T>; the gather (periodic self-copy + pack of the send cells, one launch) and
5// the unpack (scatter into ghost cells) run as Kokkos::parallel_for on the default execution space
6// (CUDA / HIP / OpenMP) — on a host memory space a copy of at most kHaloSerialCopy elements runs on
7// the calling thread instead (no parallel region) — so the full field never crosses the bus — only
8// the compact halo buffers are staged to the host for MPI. The GPU-aware-MPI path (hand device
9// pointers straight to MPI, dropping both staging copies) is the DEFAULT on device builds when a
10// loopback probe confirms MPI accepts device pointers; env PECLET_CORE_GPU_AWARE_MPI=0 forces host
11// staging (kill switch for stacks that segfault instead of erroring), =1 forces the device path
12// without probing (legacy PECLET_CORE_CUDA_AWARE_MPI honoured). exchangeBegin/exchangeEnd expose
13// the split so callers can overlap interior compute with the messages in flight; exchange() is the
14// blocking composition. Topology comes from a host-built GridHaloTopology<Dim>::flatten(), and the
15// result is bit-for-bit identical to the CPU exchange.
16//
17// On a host memory space, partners on the same node exchange through MPI-3 shared memory (flow
18// doc/vof_distributed_host_comm_design.md §5.5, WO-K5): init() allocates, per instance and node,
19// a shared window that holds every rank's receive slots (two parities per on-node sender) and the
20// per-sender flags seq[2] / consumed; the gather writes an on-node payload straight into the
21// receiver's slot and publishes it with a release store of the exchange's sequence number, so the
22// data lands during the sender's pack and the begin/interior/end overlap is real. Off-node
23// partners keep the persistent MPI requests. The bytes moved are identical. PECLET_CORE_HALO_SHM=0
24// is the debug kill switch (bitwise-neutral: every partner then goes through MPI, as before K5);
25// PECLET_CORE_HALO_SHM_GROUP=k splits each node into groups of k ranks, so one node runs the mixed
26// on-node / off-node path of a multi-node job (debug, bitwise-neutral). Both must be the same on
27// every rank: init checks that with one allreduce and throws on a mismatch.
28//
29// GridHalo init and destruction are COLLECTIVE over the communicator on a host memory space with
30// more than one rank (node split, MPI_Win_allocate_shared, MPI_Win_free): create, re-init and
31// destroy every instance on every rank, in the same order. From Python, release solvers on every
32// rank (del + an explicit teardown at the same point of the program); do not rely on the garbage
33// collector, whose timing differs between ranks.
34#ifndef PECLET_CORE_HALO_GRID_HALO_HPP
35#define PECLET_CORE_HALO_GRID_HALO_HPP
36
37#include <atomic>
38#include <cstdint>
39#include <cstdio>
40#include <cstdlib>
41#include <cstring>
42#include <stdexcept>
43#include <string>
44#include <thread>
45#include <type_traits>
46#include <vector>
47
49#if __has_include(<mpi-ext.h>)
50#include <mpi-ext.h> // OpenMPI: MPIX_CUDA_AWARE_SUPPORT / MPIX_Query_cuda_support
51#endif
55
57
58namespace detail {
63inline bool mpiReportsCudaAware() {
64#if defined(MPIX_CUDA_AWARE_SUPPORT)
65#if MPIX_CUDA_AWARE_SUPPORT
66 return MPIX_Query_cuda_support() == 1;
67#else
68 return false;
69#endif
70#else
71 return false; // no query available: no signal
72#endif
73}
74
82inline bool probeGpuAwareMpi() {
83#ifdef KOKKOS_ENABLE_SERIAL
84 if (std::is_same_v<ExecSpace, Kokkos::Serial>)
85 return false; // host backend: device pointers are host pointers; staging copies alias anyway
86#endif
87#ifdef KOKKOS_ENABLE_OPENMP
88 if (std::is_same_v<ExecSpace, Kokkos::OpenMP>)
89 return false;
90#endif
91#ifdef KOKKOS_ENABLE_THREADS
92 if (std::is_same_v<ExecSpace, Kokkos::Threads>)
93 return false; // host backend, same as the two above — a wheel without a usable OpenMP gets
94 // this
95#endif
96 int inited = 0;
97 MPI_Initialized(&inited);
98 if (!inited)
99 return false;
100 MPI_Comm self;
101 if (MPI_Comm_dup(MPI_COMM_SELF, &self) != MPI_SUCCESS)
102 return false;
103 MPI_Comm_set_errhandler(self, MPI_ERRORS_RETURN);
104 constexpr int N = 64;
105 View<int> src(Kokkos::view_alloc("peclet::core::halo::probeSrc", Kokkos::WithoutInitializing), N);
106 View<int> dst("peclet::core::halo::probeDst", N);
107 Kokkos::parallel_for(
108 "peclet::core::halo::probeFill", Kokkos::RangePolicy<ExecSpace>(0, N),
109 KOKKOS_LAMBDA(const int i) { src(i) = 0x5EC0DE + i * 7919; });
110 Kokkos::fence();
111 const int rc = MPI_Sendrecv(src.data(), N, MPI_INT, 0, 77, dst.data(), N, MPI_INT, 0, 77, self,
113 MPI_Comm_free(&self);
114 if (rc != MPI_SUCCESS)
115 return false;
116 int bad = 1;
117 Kokkos::parallel_reduce(
118 "peclet::core::halo::probeCheck", Kokkos::RangePolicy<ExecSpace>(0, N),
119 KOKKOS_LAMBDA(const int i, int& b) {
120 if (dst(i) != 0x5EC0DE + i * 7919)
121 b += 1;
122 },
123 bad);
124 return bad == 0;
125}
126
135inline bool gpuAwareMpi() {
136 static const bool v = [] {
137 const char* e = std::getenv("PECLET_CORE_GPU_AWARE_MPI");
138 if (!e)
139 e = std::getenv("PECLET_CORE_CUDA_AWARE_MPI");
140 const bool aware = e ? (std::atoi(e) != 0) : (mpiReportsCudaAware() && probeGpuAwareMpi());
141 if (std::getenv("PECLET_CORE_HALO_VERBOSE"))
142 std::fprintf(stderr, "peclet.core halo: %s MPI buffers (%s)\n",
143 aware ? "DEVICE" : "host-staged", e ? "env-forced" : "auto");
144 return aware;
145 }();
146 return v;
147}
148
151inline double haloTimeout() {
152 static const double v = [] {
153 const char* e = std::getenv("PECLET_CORE_HALO_TIMEOUT");
154 return e ? std::atof(e) : 0.0;
155 }();
156 return v;
157}
158
162inline bool haloShmEnabled() {
163 static const bool v = [] {
164 const char* e = std::getenv("PECLET_CORE_HALO_SHM");
165 return !(e && std::atoi(e) == 0);
166 }();
167 return v;
168}
169
176inline int haloShmGroup() {
177 static const int v = [] {
178 const char* e = std::getenv("PECLET_CORE_HALO_SHM_GROUP");
179 const int k = e ? std::atoi(e) : 0;
180 return k > 0 ? k : 0;
181 }();
182 return v;
183}
184} // namespace detail
185
190inline constexpr Index kHaloSerialCopy = 2048;
191
195inline constexpr int kHaloShmSpin = 256;
196
200template <class T>
201class GridHalo {
202 public:
203 GridHalo() = default;
204 GridHalo(const GridHalo&) = delete;
205 GridHalo& operator=(const GridHalo&) = delete;
207 freePersistent();
208 freeShm();
209 }
210
221 template <int Dim>
222 void init(const GridHaloTopology<Dim>& halo, int stack = 1, Index stride = 0) {
223 auto t = stack > 1 ? halo.flatten().stacked(stack, stride) : halo.flatten();
224 comm_ = t.comm;
225 sendRanks_ = t.sendRanks;
226 recvRanks_ = t.recvRanks;
227 sendCounts_ = t.sendCounts;
228 recvCounts_ = t.recvCounts;
229
230 sendOff_.assign(sendCounts_.size() + 1, 0);
231 for (std::size_t k = 0; k < sendCounts_.size(); ++k)
232 sendOff_[k + 1] = sendOff_[k] + sendCounts_[k];
233 recvOff_.assign(recvCounts_.size() + 1, 0);
234 for (std::size_t k = 0; k < recvCounts_.size(); ++k)
235 recvOff_[k + 1] = recvOff_[k] + recvCounts_[k];
236
237 nSend_ = static_cast<Index>(t.sendIdx.size());
238 nRecv_ = static_cast<Index>(t.recvIdx.size());
239 nSelf_ = static_cast<Index>(t.selfSrc.size());
240
241 d_sendIdx_ = toDevice(t.sendIdx, "peclet::core::halo::sendIdx");
242 d_recvIdx_ = toDevice(t.recvIdx, "peclet::core::halo::recvIdx");
243 d_selfSrc_ = toDevice(t.selfSrc, "peclet::core::halo::selfSrc");
244 d_selfDst_ = toDevice(t.selfDst, "peclet::core::halo::selfDst");
245 d_sendBuf_ =
246 View<T>(Kokkos::view_alloc("peclet::core::halo::sendBuf", Kokkos::WithoutInitializing),
247 static_cast<std::size_t>(nSend_));
248 d_recvBuf_ =
249 View<T>(Kokkos::view_alloc("peclet::core::halo::recvBuf", Kokkos::WithoutInitializing),
250 static_cast<std::size_t>(nRecv_));
251 h_sendBuf_ = Kokkos::create_mirror_view(d_sendBuf_);
252 h_recvBuf_ = Kokkos::create_mirror_view(d_recvBuf_);
253 // The on-node shared-memory slots first (they decide which partners stay on MPI), then the
254 // persistent requests for the rest, on the buffers the staging choice selects (cached here; a
255 // later flip re-inits them in exchangeBegin).
256 initShm();
257 initPersistent(detail::gpuAwareMpi());
258 }
259
262 void setLabel(std::string label) { label_ = std::move(label); }
263
267 int numShmPartners() const { return static_cast<int>(shmSend_.size() + shmRecv_.size()); }
268
270 void exchange(const View<T>& field, int tag = 0) {
271 exchangeBegin(field, tag);
272 exchangeEnd(field);
273 }
274
281 void exchangeBegin(const View<T>& field, int tag = 0) {
282 const bool aware = detail::gpuAwareMpi();
283 const bool shm = tag == 0 && shm_;
284 // Exchange s of this instance (on-node transport): its payloads go into the parity-(s & 1)
285 // slots, which exchange s - 2 used, so each on-node receiver must have consumed s - 2 first.
286 std::uint64_t s = 0;
287 if (shm) {
288 s = ++seq_;
289 waitSlotsConsumed(s);
290 }
291 // The gather: the periodic self-copy (read inner cell, write ghost cell) and the pack of the
292 // send cells — into the contiguous send buffer, or for an on-node receiver straight into its
293 // slot — as ONE launch over [0, nSelf_ + nSend_). Race-free for any ghost width: the self-copy
294 // writes ghost cells only and the pack reads inner cells only. On a host memory space at most
295 // kHaloSerialCopy elements are copied by the calling thread. (Inline, not a private helper:
296 // nvcc rejects an extended lambda in a private member function.)
297 if (nSelf_ + nSend_) {
298 const Index nSelf = nSelf_, nAll = nSelf_ + nSend_;
299 View<T> f = field;
300 IndexView src = d_selfSrc_, dst = d_selfDst_, idx = d_sendIdx_;
301 View<T> buf = d_sendBuf_;
302 if constexpr (kHostMemory) {
303 if (shm) {
304 T* const* out = sendDst_[s & 1].data(); // per send element: its slot or buffer entry
305 if (nAll <= kHaloSerialCopy) {
306 Kokkos::fence(); // the caller's kernels on `field` are complete before the thread
307 // reads
308 for (Index i = 0; i < nSelf; ++i)
309 f(dst(i)) = f(src(i));
310 for (Index i = nSelf; i < nAll; ++i)
311 *out[i - nSelf] = f(idx(i - nSelf));
312 } else {
313 Kokkos::parallel_for(
314 "peclet::core::halo::gather", Kokkos::RangePolicy<ExecSpace>(0, nAll),
315 KOKKOS_LAMBDA(const Index i) {
316 if (i < nSelf)
317 f(dst(i)) = f(src(i));
318 else
319 *out[i - nSelf] = f(idx(i - nSelf));
320 });
321 }
322 }
323 }
324 if (!shm) {
325 if (kHostMemory && nAll <= kHaloSerialCopy) {
326 Kokkos::fence(); // the caller's kernels on `field` are complete before the thread reads
327 for (Index i = 0; i < nSelf; ++i)
328 f(dst(i)) = f(src(i));
329 for (Index i = nSelf; i < nAll; ++i)
330 buf(i - nSelf) = f(idx(i - nSelf));
331 } else {
332 Kokkos::parallel_for(
333 "peclet::core::halo::gather", Kokkos::RangePolicy<ExecSpace>(0, nAll),
334 KOKKOS_LAMBDA(const Index i) {
335 if (i < nSelf)
336 f(dst(i)) = f(src(i));
337 else
338 buf(i - nSelf) = f(idx(i - nSelf));
339 });
340 }
341 }
342 }
343 // The send buffer (host-staged, or device for the aware path) must be ready before MPI reads
344 // it, and on the aware path the previous exchange's unpack must be done reading the receive
345 // buffer MPI is about to fill. Host staging: the two-argument deep_copy fences. With no MPI
346 // traffic (np 1: self-copy only) nothing outside the execution space reads either buffer —
347 // the gather is stream-ordered before the caller's next kernel — so there is no fence. The
348 // same fence completes the gather into the on-node slots before their release below.
349 if (nSend_ && !aware)
350 Kokkos::deep_copy(h_sendBuf_, d_sendBuf_);
351 if (!recvRanks_.empty() || !sendRanks_.empty())
352 Kokkos::fence("peclet::core::halo::beforeMpi");
353 if (shm)
354 publishSlots(s);
355
356 inFlightAware_ = aware;
357 inFlightShm_ = shm;
358 if (tag == 0 && usePersistent_ && aware != preqAware_)
359 initPersistent(aware);
360 if (tag == 0 && usePersistent_) {
361 if (!preqs_.empty())
362 MPI_Startall(static_cast<int>(preqs_.size()), preqs_.data());
363 inFlightPersistent_ = true;
364 return;
365 }
366 inFlightPersistent_ = false;
367 postMessages(tag, aware, shm);
368 }
369
372 void exchangeEnd(const View<T>& field) {
373 std::vector<MPI_Request>& r = inFlightPersistent_ ? preqs_ : reqs_;
374 const std::vector<int>& peer = inFlightPersistent_ ? preqPeer_ : reqPeer_;
375 if (!r.empty()) {
376 if (detail::haloTimeout() > 0)
377 waitAllDiagnosed(r, peer, detail::haloTimeout());
378 else
379 MPI_Waitall(static_cast<int>(r.size()), r.data(), MPI_STATUSES_IGNORE);
380 }
381 reqs_.clear();
382 inFlightPersistent_ = false;
383 // On-node transport: after the MPI completion (so no request of this exchange needs this rank
384 // inside MPI while it polls), wait until every on-node sender has published exchange s.
385 const bool shm = inFlightShm_;
386 inFlightShm_ = false;
387 const std::uint64_t s = seq_;
388 if (shm)
389 for (const ShmPeer& p : shmRecv_)
390 shmWait([&] { return load(p.seq[s & 1]) == s; }, "DATA from", recvRanks_[p.k], s);
391 if (nRecv_) {
392 if (!inFlightAware_)
393 Kokkos::deep_copy(d_recvBuf_, h_recvBuf_);
394 View<T> f = field;
395 IndexView idx = d_recvIdx_;
396 View<T> buf = d_recvBuf_;
397 bool done = false;
398 if constexpr (kHostMemory) {
399 if (shm) {
400 const T* const* in = recvSrc_[s & 1].data(); // per receive element: slot or buffer
401 if (nRecv_ <= kHaloSerialCopy) {
402 for (Index i = 0; i < nRecv_; ++i)
403 f(idx(i)) = *in[i];
404 } else {
405 Kokkos::parallel_for(
406 "peclet::core::halo::unpack", Kokkos::RangePolicy<ExecSpace>(0, nRecv_),
407 KOKKOS_LAMBDA(const Index i) { f(idx(i)) = *in[i]; });
408 Kokkos::fence("peclet::core::halo::afterShmUnpack"); // slots read before released
409 }
410 done = true;
411 } else if (nRecv_ <= kHaloSerialCopy) {
412 for (Index i = 0; i < nRecv_; ++i)
413 f(idx(i)) = buf(i);
414 done = true;
415 }
416 }
417 if (!done) {
418 Kokkos::parallel_for(
419 "peclet::core::halo::unpack", Kokkos::RangePolicy<ExecSpace>(0, nRecv_),
420 KOKKOS_LAMBDA(const Index i) { f(idx(i)) = buf(i); });
421 // The unpack is stream-ordered before the caller's next kernel and is not fenced. The
422 // aware path keeps one fence: a caller may hand the exchanged device field straight to
423 // MPI. (Host staging: the receive buffer was copied by a fencing deep_copy above.)
424 if (inFlightAware_)
425 Kokkos::fence("peclet::core::halo::afterUnpack");
426 }
427 }
428 // Hand the parity-(s & 1) slots back to their senders (exchange s + 2 may refill them).
429 if (shm)
430 for (const ShmPeer& p : shmRecv_)
431 store(p.consumed, s);
432 }
433
434 private:
435 static constexpr bool kHostMemory = std::is_same_v<MemSpace, Kokkos::HostSpace>;
436 static constexpr std::size_t kLine = 64; // one flag per cache line; slots line-aligned
437 static_assert(std::atomic_ref<std::uint64_t>::is_always_lock_free,
438 "the on-node flags need lock-free 64-bit atomics (address-free across processes)");
439
440 // ---- the lambda-free phases of exchangeBegin (nvcc keeps the gather launches inline there) ----
441
444 void waitSlotsConsumed(std::uint64_t s) {
445 for (const ShmPeer& p : shmSend_)
446 shmWait([&] { return load(p.consumed) + 2 >= s; }, "CONSUMED by", sendRanks_[p.k], s);
447 }
448
450 void publishSlots(std::uint64_t s) {
451 std::atomic_thread_fence(std::memory_order_release);
452 for (const ShmPeer& p : shmSend_)
453 store(p.seq[s & 1], s);
454 }
455
458 void postMessages(int tag, bool aware, bool shm) {
459 T* sendBase = aware ? d_sendBuf_.data() : h_sendBuf_.data();
460 T* recvBase = aware ? d_recvBuf_.data() : h_recvBuf_.data();
461 reqs_.clear();
462 reqs_.reserve(recvRanks_.size() + sendRanks_.size());
463 reqPeer_.clear();
464 for (std::size_t k = 0; k < recvRanks_.size(); ++k) {
465 if (shm && recvShm_[k])
466 continue; // (persistent requests unavailable) the on-node payloads come through the slots
467 reqs_.emplace_back();
468 reqPeer_.push_back(static_cast<int>(k));
469 MPI_Irecv(recvBase + recvOff_[k], recvCounts_[k] * static_cast<int>(sizeof(T)), MPI_BYTE,
470 recvRanks_[k], tag, comm_, &reqs_.back());
471 }
472 for (std::size_t k = 0; k < sendRanks_.size(); ++k) {
473 if (shm && sendShm_[k])
474 continue;
475 reqs_.emplace_back();
476 reqPeer_.push_back(static_cast<int>(recvRanks_.size() + k));
477 MPI_Isend(sendBase + sendOff_[k], sendCounts_[k] * static_cast<int>(sizeof(T)), MPI_BYTE,
478 sendRanks_[k], tag, comm_, &reqs_.back());
479 }
480 }
481
484 struct ShmPeer {
485 int k = 0; // index into sendRanks_ / recvRanks_
486 std::uint64_t* seq[2] = {nullptr, nullptr}; // last exchange published in parity 0 / 1
487 std::uint64_t* consumed = nullptr; // last exchange the receiver has unpacked
488 };
489
490 static std::uint64_t load(std::uint64_t* p) {
491 return std::atomic_ref<std::uint64_t>(*p).load(std::memory_order_acquire);
492 }
493 static void store(std::uint64_t* p, std::uint64_t v) {
494 std::atomic_ref<std::uint64_t>(*p).store(v, std::memory_order_release);
495 }
496 static void cpuRelax() {
497#if defined(__x86_64__) || defined(__i386__)
498 __builtin_ia32_pause();
499#elif defined(__aarch64__)
500 asm volatile("yield");
501#endif
502 }
503
510 template <class Done>
511 void shmWait(Done done, const char* what, int partner, std::uint64_t s) {
512 if (done())
513 return;
514 const double timeout = detail::haloTimeout();
515 const double t0 = timeout > 0 ? MPI_Wtime() : 0.0;
516 for (int n = 1;; ++n) {
517 if (done())
518 return;
519 if (n < kHaloShmSpin) {
520 cpuRelax();
521 continue;
522 }
523 n = 0;
524 std::this_thread::yield();
525 int pending = 0;
526 MPI_Iprobe(MPI_ANY_SOURCE, MPI_ANY_TAG, comm_, &pending, MPI_STATUS_IGNORE);
527 if (timeout > 0 && MPI_Wtime() - t0 >= timeout) {
528 std::string msg = timeoutHeader(timeout) + " pending shared-memory " + what + " comm " +
529 std::to_string(partner) + " (world " +
530 std::to_string(worldRank(partner)) + "), exchange " + std::to_string(s) +
531 "\n";
532 std::fputs(msg.c_str(), stderr);
533 std::fflush(stderr);
535 }
536 }
537 }
538
542 void initShm() {
543 freeShm();
544 sendShm_.assign(sendRanks_.size(), 0);
545 recvShm_.assign(recvRanks_.size(), 0);
546 if constexpr (kHostMemory) {
547 int csize = 1;
548 MPI_Comm_size(comm_, &csize);
549 if (csize < 2)
550 return;
551 checkShmEnvCollective();
553 return;
554 int nsize = 1;
555 if (!openNodeComm(nsize))
556 return;
557 // Which partners share the node: their rank in node_ (MPI_UNDEFINED when off-node).
558 std::vector<int> sendNode(sendRanks_.size(), MPI_UNDEFINED);
559 std::vector<int> recvNode(recvRanks_.size(), MPI_UNDEFINED);
560 nodeRanks(sendNode, recvNode);
561 // This rank's segment (the per-sender blocks) and the shared window that holds it.
562 std::vector<std::size_t> recvBlock(recvRanks_.size(), 0);
563 const std::size_t bytes = segmentLayout(recvNode, recvBlock);
564 void* base = nullptr;
565 if (!allocateWindow(bytes, base))
566 return;
567 MPI_Win_lock_all(MPI_MODE_NOCHECK, win_);
568 winLocked_ = true;
569 // Line-align the segment in this rank's view (the mapping is page-aligned in every process,
570 // so the same offsets are line-aligned in the senders' views too); zero it, so every flag
571 // starts at 0 (no exchange published, none consumed) before any partner reads it.
572 const std::size_t pad = (kLine - reinterpret_cast<std::uintptr_t>(base) % kLine) % kLine;
573 char* own = static_cast<char*>(base) + pad;
574 std::memset(own, 0, bytes);
575 MPI_Win_sync(win_);
576 MPI_Barrier(node_);
577 // Tell every on-node sender where its block sits in this segment, and the count expected.
578 const std::vector<std::int64_t> in = exchangeLayout(recvNode, recvBlock, pad, nsize);
579
580 for (int p = 0; p < 2; ++p) {
581 sendDst_[p].resize(static_cast<std::size_t>(nSend_));
582 recvSrc_[p].resize(static_cast<std::size_t>(nRecv_));
583 }
584 mapSendSlots(sendNode, in);
585 mapRecvSlots(recvNode, recvBlock, own);
586 shm_ = true;
587 }
588 }
589
590 // ---- the phases of initShm (collective in the order initShm calls them) ----------------------
591
594 bool openNodeComm(int& nsize) {
595 MPI_Comm_split_type(comm_, MPI_COMM_TYPE_SHARED, 0, MPI_INFO_NULL, &node_);
596 if (const int k = detail::haloShmGroup(); k > 0) { // debug sub-split (mixed transport)
597 int nodeRank = 0;
598 MPI_Comm_rank(node_, &nodeRank);
599 MPI_Comm group = MPI_COMM_NULL;
600 MPI_Comm_split(node_, nodeRank / k, nodeRank, &group);
601 MPI_Comm_free(&node_);
602 node_ = group;
603 }
604 MPI_Comm_size(node_, &nsize);
605 if (nsize < 2) { // every member of this node communicator sees the same size
606 MPI_Comm_free(&node_);
607 return false;
608 }
609 return true;
610 }
611
613 void nodeRanks(std::vector<int>& sendNode, std::vector<int>& recvNode) const {
614 MPI_Group cg, ng;
615 MPI_Comm_group(comm_, &cg);
616 MPI_Comm_group(node_, &ng);
617 if (!sendRanks_.empty())
618 MPI_Group_translate_ranks(cg, static_cast<int>(sendRanks_.size()), sendRanks_.data(), ng,
619 sendNode.data());
620 if (!recvRanks_.empty())
621 MPI_Group_translate_ranks(cg, static_cast<int>(recvRanks_.size()), recvRanks_.data(), ng,
622 recvNode.data());
623 MPI_Group_free(&cg);
624 MPI_Group_free(&ng);
625 }
626
628 static std::size_t slotBytes(int count) {
629 return (static_cast<std::size_t>(count) * sizeof(T) + kLine - 1) / kLine * kLine;
630 }
631
635 std::size_t segmentLayout(const std::vector<int>& recvNode, std::vector<std::size_t>& recvBlock) {
636 std::size_t bytes = 0;
637 for (std::size_t k = 0; k < recvRanks_.size(); ++k)
638 if (recvNode[k] != MPI_UNDEFINED) {
639 recvBlock[k] = bytes;
640 bytes += 3 * kLine + 2 * slotBytes(recvCounts_[k]);
641 }
642 return bytes;
643 }
644
647 bool allocateWindow(std::size_t bytes, void*& base) {
648 MPI_Info info;
649 MPI_Info_create(&info);
650 MPI_Info_set(info, "alloc_shared_noncontig", "true");
651 MPI_Win_allocate_shared(static_cast<MPI_Aint>(bytes + kLine), 1, info, node_, &base, &win_);
652 MPI_Info_free(&info);
653 // The unified memory model (load/store = the window's public copy), on every member.
654 int* model = nullptr;
655 int flag = 0;
656 MPI_Win_get_attr(win_, MPI_WIN_MODEL, &model, &flag);
657 int unified = (flag && *model == MPI_WIN_UNIFIED) ? 1 : 0, allUnified = 0;
658 MPI_Allreduce(&unified, &allUnified, 1, MPI_INT, MPI_MIN, node_);
659 if (!allUnified) {
660 MPI_Win_free(&win_);
661 MPI_Comm_free(&node_);
662 return false;
663 }
664 return true;
665 }
666
669 std::vector<std::int64_t> exchangeLayout(const std::vector<int>& recvNode,
670 const std::vector<std::size_t>& recvBlock,
671 std::size_t pad, int nsize) {
672 std::vector<std::int64_t> out(2 * static_cast<std::size_t>(nsize), -1),
673 in(2 * static_cast<std::size_t>(nsize), -1);
674 for (std::size_t k = 0; k < recvRanks_.size(); ++k)
675 if (recvNode[k] != MPI_UNDEFINED) {
676 out[2 * static_cast<std::size_t>(recvNode[k])] =
677 static_cast<std::int64_t>(pad + recvBlock[k]);
678 out[2 * static_cast<std::size_t>(recvNode[k]) + 1] = recvCounts_[k];
679 }
680 MPI_Alltoall(out.data(), 2, MPI_INT64_T, in.data(), 2, MPI_INT64_T, node_);
681 return in;
682 }
683
685 static ShmPeer peerAt(char* blk, int k) {
686 ShmPeer p;
687 p.k = k;
688 p.seq[0] = reinterpret_cast<std::uint64_t*>(blk);
689 p.seq[1] = reinterpret_cast<std::uint64_t*>(blk + kLine);
690 p.consumed = reinterpret_cast<std::uint64_t*>(blk + 2 * kLine);
691 return p;
692 }
693
695 void mapSendSlots(const std::vector<int>& sendNode, const std::vector<std::int64_t>& in) {
696 for (std::size_t k = 0; k < sendRanks_.size(); ++k) {
697 T* priv = d_sendBuf_.data() + sendOff_[k];
698 T* slot[2] = {priv, priv};
699 if (sendNode[k] != MPI_UNDEFINED) {
700 const std::size_t q = static_cast<std::size_t>(sendNode[k]);
701 if (in[2 * q] < 0 || in[2 * q + 1] != sendCounts_[k]) {
702 std::fprintf(stderr,
703 "peclet.core halo [%s]: on-node layout mismatch with node rank %d (offset "
704 "%lld, count %lld, expected %d)\n",
705 label_.c_str(), sendNode[k], static_cast<long long>(in[2 * q]),
706 static_cast<long long>(in[2 * q + 1]), sendCounts_[k]);
708 }
709 MPI_Aint sz = 0;
710 int du = 1;
711 void* rb = nullptr;
712 MPI_Win_shared_query(win_, sendNode[k], &sz, &du, &rb);
713 char* blk = static_cast<char*>(rb) + in[2 * q];
714 shmSend_.push_back(peerAt(blk, static_cast<int>(k)));
715 sendShm_[k] = 1;
716 slot[0] = reinterpret_cast<T*>(blk + 3 * kLine);
717 slot[1] = reinterpret_cast<T*>(blk + 3 * kLine + slotBytes(sendCounts_[k]));
718 }
719 for (int p = 0; p < 2; ++p)
720 for (int j = 0; j < sendCounts_[k]; ++j)
721 sendDst_[p][static_cast<std::size_t>(sendOff_[k] + j)] = slot[p] + j;
722 }
723 }
724
727 void mapRecvSlots(const std::vector<int>& recvNode, const std::vector<std::size_t>& recvBlock,
728 char* own) {
729 for (std::size_t k = 0; k < recvRanks_.size(); ++k) {
730 const T* priv = d_recvBuf_.data() + recvOff_[k];
731 const T* slot[2] = {priv, priv};
732 if (recvNode[k] != MPI_UNDEFINED) {
733 char* blk = own + recvBlock[k];
734 shmRecv_.push_back(peerAt(blk, static_cast<int>(k)));
735 recvShm_[k] = 1;
736 slot[0] = reinterpret_cast<const T*>(blk + 3 * kLine);
737 slot[1] = reinterpret_cast<const T*>(blk + 3 * kLine + slotBytes(recvCounts_[k]));
738 }
739 for (int p = 0; p < 2; ++p)
740 for (int j = 0; j < recvCounts_[k]; ++j)
741 recvSrc_[p][static_cast<std::size_t>(recvOff_[k] + j)] = slot[p] + j;
742 }
743 }
744
748 void checkShmEnvCollective() const {
749 const int en = detail::haloShmEnabled() ? 1 : 0, grp = detail::haloShmGroup();
750 int v[4] = {en, -en, grp, -grp};
751 MPI_Allreduce(MPI_IN_PLACE, v, 4, MPI_INT, MPI_MAX, comm_);
752 if (v[0] != -v[1] || v[2] != -v[3])
753 throw std::runtime_error(
754 "peclet.core halo [" + label_ +
755 "]: PECLET_CORE_HALO_SHM / PECLET_CORE_HALO_SHM_GROUP differ across the ranks of the "
756 "communicator (shared memory on " +
757 std::to_string(-v[1]) + ".." + std::to_string(v[0]) + ", group " + std::to_string(-v[3]) +
758 ".." + std::to_string(v[2]) + "); set them identically on every rank (mpirun -x)");
759 }
760
763 void freeShm() {
764 shm_ = false;
765 inFlightShm_ = false;
766 seq_ = 0;
767 shmSend_.clear();
768 shmRecv_.clear();
769 for (int p = 0; p < 2; ++p) {
770 sendDst_[p].clear();
771 recvSrc_[p].clear();
772 }
773 if (win_ == MPI_WIN_NULL && node_ == MPI_COMM_NULL)
774 return;
775 int fin = 0;
776 MPI_Finalized(&fin);
777 if (!fin) {
778 if (win_ != MPI_WIN_NULL) {
779 if (winLocked_)
780 MPI_Win_unlock_all(win_);
781 MPI_Win_free(&win_);
782 }
783 if (node_ != MPI_COMM_NULL)
784 MPI_Comm_free(&node_);
785 }
786 winLocked_ = false;
787 win_ = MPI_WIN_NULL;
788 node_ = MPI_COMM_NULL;
789 }
790
795 void initPersistent(bool aware) {
796 freePersistent();
797 preqAware_ = aware;
798 T* sendBase = aware ? d_sendBuf_.data() : h_sendBuf_.data();
799 T* recvBase = aware ? d_recvBuf_.data() : h_recvBuf_.data();
800 preqs_.clear();
801 preqPeer_.clear();
802 bool ok = true;
803 for (std::size_t k = 0; k < recvRanks_.size(); ++k) {
804 if (shm_ && recvShm_[k])
805 continue;
806 preqs_.push_back(MPI_REQUEST_NULL);
807 preqPeer_.push_back(static_cast<int>(k));
808 ok &= MPI_Recv_init(recvBase + recvOff_[k], recvCounts_[k] * static_cast<int>(sizeof(T)),
809 MPI_BYTE, recvRanks_[k], 0, comm_, &preqs_.back()) == MPI_SUCCESS;
810 }
811 const std::size_t nr = recvRanks_.size();
812 for (std::size_t k = 0; k < sendRanks_.size(); ++k) {
813 if (shm_ && sendShm_[k])
814 continue;
815 preqs_.push_back(MPI_REQUEST_NULL);
816 preqPeer_.push_back(static_cast<int>(nr + k));
817 ok &= MPI_Send_init(sendBase + sendOff_[k], sendCounts_[k] * static_cast<int>(sizeof(T)),
818 MPI_BYTE, sendRanks_[k], 0, comm_, &preqs_.back()) == MPI_SUCCESS;
819 }
820 if (!ok)
821 freePersistent();
822 usePersistent_ = ok;
823 }
824
825 void freePersistent() {
826 usePersistent_ = false;
827 if (preqs_.empty())
828 return;
829 int fin = 0;
830 MPI_Finalized(&fin);
831 if (!fin)
832 for (auto& r : preqs_)
833 if (r != MPI_REQUEST_NULL)
834 MPI_Request_free(&r);
835 preqs_.clear();
836 preqPeer_.clear();
837 }
838
839 MPI_Comm comm_ = MPI_COMM_NULL;
840 std::vector<int> sendRanks_, recvRanks_, sendCounts_, recvCounts_;
841 std::vector<int> sendOff_, recvOff_;
842 std::vector<MPI_Request> reqs_; // in-flight Isend/Irecv (tag != 0) between begin and end
843 std::vector<MPI_Request> preqs_; // persistent: receives then sends, on preqAware_'s buffers
844 std::vector<int> reqPeer_, preqPeer_; // per request: recv neighbour k, or nRecvRanks + send k
845 bool usePersistent_ = false; // preqs_ built (false: init failed, or no init yet)
846 bool preqAware_ = false; // staging mode preqs_ were built for
847 bool inFlightPersistent_ = false; // the in-flight exchange runs on preqs_
848 bool inFlightAware_ = false; // staging mode of the in-flight exchange
849 Index nSend_ = 0, nRecv_ = 0, nSelf_ = 0;
850 std::string label_;
851 IndexView d_sendIdx_, d_recvIdx_, d_selfSrc_, d_selfDst_;
852
853 // On-node shared-memory transport (host memory space only; empty otherwise).
854 MPI_Comm node_ = MPI_COMM_NULL; // the ranks of comm_ on this node (MPI_COMM_TYPE_SHARED)
855 MPI_Win win_ = MPI_WIN_NULL; // every node rank's receive segment
856 bool winLocked_ = false; // the passive-target epoch (lock_all) of win_ is open
857 bool shm_ = false; // on-node partners use the window
858 bool inFlightShm_ = false; // the in-flight exchange uses it
859 std::uint64_t seq_ = 0; // exchanges of this instance on the window (s of the last)
860 std::vector<char> sendShm_, recvShm_; // per send / receive neighbour: on the window?
861 std::vector<ShmPeer> shmSend_, shmRecv_; // the on-node receivers / senders
862 std::vector<T*> sendDst_[2]; // per parity, per send element: slot or sendBuf entry
863 std::vector<const T*> recvSrc_[2]; // per parity, per receive element: slot or recvBuf
864
865 int worldRank(int r) const {
866 MPI_Group g, wg;
867 MPI_Comm_group(comm_, &g);
868 MPI_Comm_group(MPI_COMM_WORLD, &wg);
869 int w = -1;
870 MPI_Group_translate_ranks(g, 1, &r, wg, &w);
871 MPI_Group_free(&g);
872 MPI_Group_free(&wg);
873 return w;
874 }
875 std::string timeoutHeader(double timeout) const {
876 int rank = -1, size = -1, wrank = -1, wsize = -1;
877 MPI_Comm_rank(comm_, &rank);
878 MPI_Comm_size(comm_, &size);
881 return "peclet.core halo TIMEOUT after " + std::to_string(int(timeout)) + " s [" + label_ +
882 "] world " + std::to_string(wrank) + "/" + std::to_string(wsize) + " comm " +
883 std::to_string(rank) + "/" + std::to_string(size) + ": " +
884 std::to_string(recvRanks_.size()) + " recv + " + std::to_string(sendRanks_.size()) +
885 " send partners (" + std::to_string(shmRecv_.size()) + " + " +
886 std::to_string(shmSend_.size()) + " on shared memory)\n";
887 }
888
894 void waitAllDiagnosed(std::vector<MPI_Request>& reqs, const std::vector<int>& peer,
895 double timeout) {
896 const double t0 = MPI_Wtime();
897 const int n = static_cast<int>(reqs.size());
898 int done = 0;
899 while (!done) {
900 MPI_Testall(n, reqs.data(), &done, MPI_STATUSES_IGNORE);
901 if (done || MPI_Wtime() - t0 < timeout)
902 continue;
903 std::string msg = timeoutHeader(timeout);
904 const std::size_t nr = recvRanks_.size();
905 for (std::size_t k = 0; k < reqs.size(); ++k) {
906 int flag = 0;
907 MPI_Request_get_status(reqs[k], &flag, MPI_STATUS_IGNORE);
908 if (flag)
909 continue;
910 const std::size_t m = static_cast<std::size_t>(peer[k]);
911 const bool recv = m < nr;
912 const int q = recv ? recvRanks_[m] : sendRanks_[m - nr];
913 const int c = recv ? recvCounts_[m] : sendCounts_[m - nr];
914 msg += std::string(" pending ") + (recv ? "RECV from" : "SEND to ") + " comm " +
915 std::to_string(q) + " (world " + std::to_string(worldRank(q)) + ") " +
916 std::to_string(c * static_cast<long>(sizeof(T))) + " bytes\n";
917 }
918 std::fputs(msg.c_str(), stderr);
919 std::fflush(stderr);
921 }
922 }
923 View<T> d_sendBuf_, d_recvBuf_;
924 HostView<T> h_sendBuf_, h_recvBuf_;
925};
926
927} // namespace peclet::core::halo
928
929#endif // PECLET_CORE_HALO_GRID_HALO_HPP
void exchangeEnd(const View< T > &field)
Complete the exchange started by exchangeBegin: wait, then scatter the received halo cells into field...
GridHalo & operator=(const GridHalo &)=delete
void init(const GridHaloTopology< Dim > &halo, int stack=1, Index stride=0)
Build the exchange from a host topology.
void exchange(const View< T > &field, int tag=0)
Exchange ghost layers of the device field field. Blocking (== exchangeBegin+exchangeEnd).
int numShmPartners() const
Number of this rank's partners (send + receive) served by the on-node shared-memory transport; 0 on a...
GridHalo(const GridHalo &)=delete
void setLabel(std::string label)
Name printed by the PECLET_CORE_HALO_TIMEOUT diagnostic (e.g.
void exchangeBegin(const View< T > &field, int tag=0)
Start an exchange: periodic self-copy and pack (ONE gather), start the receives and sends,...
#define MPI_SUCCESS
Definition mpi_stub.hpp:36
int MPI_Comm_size(MPI_Comm, int *s)
Definition mpi_stub.hpp:70
#define MPI_COMM_NULL
Definition mpi_stub.hpp:28
int MPI_Testall(int, MPI_Request *, int *flag, MPI_Status *)
Definition mpi_stub.hpp:153
int MPI_Allreduce(const void *sbuf, void *rbuf, int count, MPI_Datatype dt, MPI_Op, MPI_Comm)
Definition mpi_stub.hpp:114
int MPI_Comm
Definition mpi_stub.hpp:17
#define MPI_COMM_WORLD
Definition mpi_stub.hpp:27
int MPI_Waitall(int, MPI_Request *, MPI_Status *)
Definition mpi_stub.hpp:160
#define MPI_INT
Definition mpi_stub.hpp:39
#define MPI_REQUEST_NULL
Definition mpi_stub.hpp:29
int MPI_Comm_free(MPI_Comm *)
Definition mpi_stub.hpp:107
#define MPI_STATUS_IGNORE
Definition mpi_stub.hpp:31
#define MPI_BYTE
Definition mpi_stub.hpp:38
int MPI_Iprobe(int, int, MPI_Comm, int *flag, MPI_Status *)
Definition mpi_stub.hpp:141
#define MPI_STATUSES_IGNORE
Definition mpi_stub.hpp:32
#define MPI_MAX
Definition mpi_stub.hpp:44
int MPI_Isend(const void *, int, MPI_Datatype, int, int, MPI_Comm, MPI_Request *)
Definition mpi_stub.hpp:132
int MPI_Finalized(int *f)
Definition mpi_stub.hpp:58
#define MPI_INFO_NULL
Definition mpi_stub.hpp:30
int MPI_Abort(MPI_Comm, int code)
Definition mpi_stub.hpp:62
#define MPI_MIN
Definition mpi_stub.hpp:45
#define MPI_ANY_SOURCE
Definition mpi_stub.hpp:33
int MPI_Comm_rank(MPI_Comm, int *r)
Definition mpi_stub.hpp:66
int MPI_Initialized(int *f)
Definition mpi_stub.hpp:51
int MPI_Irecv(void *, int, MPI_Datatype, int, int, MPI_Comm, MPI_Request *)
Definition mpi_stub.hpp:135
int MPI_Barrier(MPI_Comm)
Definition mpi_stub.hpp:110
int MPI_Info
Definition mpi_stub.hpp:21
#define MPI_UNDEFINED
Definition mpi_stub.hpp:34
bool haloShmEnabled()
PECLET_CORE_HALO_SHM=0: debug kill switch for the on-node shared-memory transport (WO-K5),...
int haloShmGroup()
PECLET_CORE_HALO_SHM_GROUP=k (k > 0): debug sub-split of the on-node shared-memory transport,...
bool mpiReportsCudaAware()
Does the MPI library itself claim CUDA awareness (OpenMPI's MPIX_Query_cuda_support)?
Definition grid_halo.hpp:63
double haloTimeout()
PECLET_CORE_HALO_TIMEOUT=<seconds>: turn every exchangeEnd into a deadline wait that names the pendin...
bool gpuAwareMpi()
Whether to hand DEVICE pointers straight to MPI (GPU-aware MPI) instead of host-staging.
bool probeGpuAwareMpi()
Probe whether MPI actually accepts DEVICE pointers (GPU-aware MPI): checksummed loopback Sendrecv on ...
Definition grid_halo.hpp:82
constexpr int kHaloShmSpin
Host memory space, on-node shared-memory transport: a wait on a partner's flag polls this many times ...
constexpr Index kHaloSerialCopy
Host memory space only: a gather (self-copy + pack) or an unpack of at most this many elements runs a...
View< T > toDevice(const std::vector< T > &h, const std::string &label)
Upload a host std::vector into a freshly-sized device View (empty vector => empty view).
Definition view.hpp:44
std::int64_t Index
Signed index type for grids and particles (supersedes block_decomposer's long int IndxT).
Definition types.hpp:15
decltype(Kokkos::create_mirror_view(std::declval< View< T > >())) HostView
Host-accessible mirror of View<T> (identical to View<T> on host backends).
Definition view.hpp:31
Kokkos::View< T *, MemSpace > View
1D device array.
Definition view.hpp:26
Kokkos::View< Index *, MemSpace > IndexView
Device array of grid/particle indices (the matched send/recv/self-copy lists).
Definition view.hpp:34