ESPResSo
Extensible Simulation Package for Research on Soft Matter Systems
Loading...
Searching...
No Matches
P3MFFT.hpp
Go to the documentation of this file.
1/*
2 * Copyright (C) 2024-2026 The ESPResSo project
3 *
4 * This file is part of ESPResSo.
5 *
6 * ESPResSo is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * ESPResSo is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 */
19
20#pragma once
21
22#include "p3m/P3MFFTBackend.hpp"
23#include "p3m/common.hpp"
24
25#include "communication.hpp"
26#include "fft/vector.hpp"
27
29
30#include <utils/Vector.hpp>
31#include <utils/index.hpp>
32
33#include <boost/mpi/collectives/all_reduce.hpp>
34#include <boost/mpi/communicator.hpp>
35#include <boost/mpi/operations.hpp>
36
37#include <heffte.h>
38#include <heffte_backends.h>
39
40#include <algorithm>
41#include <array>
42#include <cstddef>
43#include <functional>
44#include <initializer_list>
45#include <limits>
46#include <memory>
47#include <type_traits>
48#include <vector>
49
50/**
51 * @brief FFT manager.
52 */
53template <typename FloatType, Arch Architecture, class FFTConfig> class P3MFFT {
54public:
55 using OutputType = typename heffte::fft_output<FloatType>::type;
56 using backend =
57 std::conditional_t<Architecture == Arch::CPU, heffte::backend::fftw,
58 heffte::backend::cufft>;
59 template <class T = OutputType>
60 using buffer_container = std::conditional_t<
61 Architecture == Arch::CPU, fft::vector<T>,
62 typename heffte::fft3d<backend>::template buffer_container<T>>;
63
64private:
65 using FFT3D =
66 std::conditional_t<FFTConfig::use_r2c, heffte::fft3d_r2c<backend>,
67 heffte::fft3d<backend>>;
68 using Box = heffte::box3d<>;
69 using stream_type =
70 heffte::backend::device_instance<heffte::tag::gpu>::stream_type;
71
72 /* input box */
73 std::unique_ptr<Box> in_box;
74 /* output box */
75 std::unique_ptr<Box> out_box;
76 /* workspace for the FFT */
78 /* FFT backend */
79 std::unique_ptr<FFT3D> fft3d;
80 std::shared_ptr<boost::mpi::environment> m_mpi_env_lock;
81 /* batched transform size */
82 unsigned m_batch_size = 0u;
83 /* whether a batched transform is both possible and faster */
84 bool use_batched_fft = false;
85
86 template <typename T, std::size_t N>
87 static auto to_array(Utils::Vector<T, N> const &vec) {
88 std::array<T, N> res{};
89 std::ranges::copy(vec, res.begin());
90 return res;
91 }
92
93 /**
94 * @brief Time the FFTs of one P3M time step on scratch buffers.
95 *
96 * One forward transform followed by @p n_fields backward transforms,
97 * either as separate calls or as one batched call. The first step is
98 * not timed: FFTW creates its plans on first use. This is a collective
99 * operation that returns the mean time per step of the slowest rank,
100 * hence all ranks get the same value.
101 */
102 static double time_fft_step(FFT3D const &fft,
103 boost::mpi::communicator const &comm, unsigned n,
104 bool batched, unsigned n_steps) {
105 using RSpaceType =
106 std::conditional_t<FFTConfig::use_r2c, FloatType, OutputType>;
107 auto const rs_size = static_cast<std::size_t>(fft.size_inbox());
108 auto const ks_size = static_cast<std::size_t>(fft.size_outbox());
109 auto const ws_size = static_cast<std::size_t>(fft.size_workspace());
110 // scratch buffers with batched size
111 buffer_container<RSpaceType> rs_buffer(n * rs_size);
112 buffer_container<OutputType> ks_buffer(n * ks_size);
113 // scratch workspace with normal buffer size if no batching was requested
114 buffer_container<OutputType> workspace((batched ? n : 1u) * ws_size);
115 auto const step = [&]() {
116 fft.forward(rs_buffer.data(), ks_buffer.data(), workspace.data());
117 if (batched) {
118 fft.backward(n, ks_buffer.data(), rs_buffer.data(), workspace.data());
119 } else {
120 for (std::size_t i = 0u; i < n; ++i) {
121 fft.backward(ks_buffer.data() + i * ks_size,
122 rs_buffer.data() + i * rs_size, workspace.data());
123 }
124 }
125 };
126 step(); // warm-up: FFTW plans are created on first use
127 comm.barrier();
128 if (n_steps == 0u) {
129 return 0.;
130 }
131 auto const tick = MPI_Wtime();
132 for (auto i = 0u; i < n_steps; ++i) {
133 step();
134 }
135 auto const tock = MPI_Wtime();
136 auto const time = (tock - tick) / static_cast<double>(n_steps);
137 return boost::mpi::all_reduce(comm, time, boost::mpi::maximum<double>());
138 }
139
140public:
142 fft3d.reset();
143 m_mpi_env_lock.reset();
144 }
145 P3MFFT(stream_type gpu_stream, boost::mpi::communicator comm,
146 Utils::Vector3i const &global_mesh,
147 Utils::Vector3i const &rs_local_ld_index,
148 Utils::Vector3i const &rs_local_ur_index,
149 Utils::Vector3i const &node_grid, unsigned n_fields = 1u) {
150 auto constexpr row_major_order = std::array<int, 3>{2, 1, 0};
151 auto constexpr col_major_order = std::array<int, 3>{0, 1, 2};
152 auto constexpr in_box_order =
153 (FFTConfig::r_space_order == Utils::MemoryOrder::ROW_MAJOR)
154 ? row_major_order
155 : col_major_order;
156 auto constexpr out_box_order =
157 (FFTConfig::k_space_order == Utils::MemoryOrder::ROW_MAJOR)
158 ? row_major_order
159 : col_major_order;
160 auto const n_procs = Utils::product(node_grid);
161 auto const high = to_array(global_mesh - Utils::Vector3i::broadcast(1));
162 auto const global_out_box_full = Box({0, 0, 0}, high, out_box_order);
163 auto const global_out_box =
164 FFTConfig::use_r2c ? global_out_box_full.r2c(FFTConfig::r2c_dir)
165 : global_out_box_full;
166 auto best_grid = node_grid;
167 for (auto i : {0u, 1u, 2u}) {
168 if (global_mesh[i] % (2 * n_procs) == 0) {
169 best_grid = {n_procs, 1, 1};
170 break;
171 }
172 }
173 m_batch_size = n_fields;
174 auto const this_rank = comm.rank();
175 // initial output boxes based on prime factors; on CPU with several ranks
176 // they only seed the plan and are replaced by its last pencil/slab stage
177 auto out_boxes = heffte::split_world(global_out_box, to_array(best_grid));
178 out_box = std::make_unique<Box>(out_boxes[this_rank]);
179
180 in_box = std::make_unique<Box>(
181 to_array(rs_local_ld_index),
182 to_array(rs_local_ur_index - Utils::Vector3i::broadcast(1)),
183 in_box_order);
184
185 // at this stage we can manually adjust some HeFFTe options
186 heffte::plan_options options = heffte::default_options<backend>();
187
188 // use strided 1-D FFT operations
189 // some backends work just as well when the entries of the data are not
190 // contiguous then there is no need to reorder the data in the intermediate
191 // stages which saves time
192 options.use_reorder = true;
193
194 // use point-to-point communications
195 // collaborative all-to-all and individual point-to-point communications are
196 // two alternatives one may be better than the other depending on the
197 // version of MPI, the hardware interconnect, and the problem size
198 options.algorithm = heffte::reshape_algorithm::p2p_plined;
199
200 // in the intermediate steps, the data can be shapes as either 2-D slabs or
201 // 1-D pencils; for sufficiently large problem, it is expected that the
202 // pencil decomposition is better but for smaller problems, the slabs may
203 // perform better (depending on hardware and backend)
204 options.use_pencils = true;
205
206 auto const make_fft3d = [&](Box const &output_box,
207 heffte::plan_options const &opts) {
208 if constexpr (FFTConfig::use_r2c) {
209 auto constexpr r2c_dir = static_cast<int>(FFTConfig::r2c_dir);
210 return std::make_unique<FFT3D>(gpu_stream, *in_box, output_box, r2c_dir,
211 comm, opts);
212 } else {
213 return std::make_unique<FFT3D>(gpu_stream, *in_box, output_box, comm,
214 opts);
215 }
216 };
217 auto const make_plan = [&](heffte::ioboxes<int> const &boxes,
218 bool use_pencils) {
219 auto opts = options;
220 opts.use_pencils = use_pencils;
221 auto constexpr r2c_dir = static_cast<int>(FFTConfig::r2c_dir);
222 return heffte::plan_operations(
223 boxes, FFTConfig::use_r2c ? r2c_dir : -1,
224 heffte::set_options<backend, FFTConfig::use_r2c>(opts), this_rank);
225 };
226 struct Candidate { // LCOV_EXCL_LINE
227 std::vector<Box> out_boxes;
228 unsigned int n_mpi_reshapes;
229 bool valid;
230 };
231 auto const is_empty = [](Box const &box) { return box.empty(); };
232 auto const make_candidate = [&](heffte::ioboxes<int> const &seed,
233 bool use_pencils) {
234 auto const seed_plan = make_plan(seed, use_pencils);
235 auto boxes = heffte::ioboxes<int>{seed.in, {}};
236 for (auto const &box : seed_plan.out_shape[2]) {
237 boxes.out.emplace_back(box.low, box.high, out_box_order);
238 }
239 auto const plan = make_plan(boxes, use_pencils);
240 auto n_mpi_reshapes = 0u;
241 auto valid = true;
242 for (auto stage : {0u, 1u, 2u, 3u}) {
243 if (not heffte::match(plan.in_shape[stage], plan.out_shape[stage])) {
244 ++n_mpi_reshapes;
245 }
246 valid &= std::ranges::none_of(plan.out_shape[stage], is_empty);
247 }
248 return Candidate{std::move(boxes.out), n_mpi_reshapes, valid};
249 };
250 // use the last FFT stage of a heFFTe plan for the input boxes as output
251 // boxes: the final reshape of each forward transform (and the first one
252 // of each backward transform) then becomes a local operation. This costs
253 // extra planning steps and one MPI_Allgather of the boxes per FFT
254 // construction. Pencils are the default; slabs need fewer MPI reshapes
255 // unless the input boxes already are slabs, but each slab reshape is an
256 // all-to-all with many more messages, so slabs are only kept when they
257 // are measured to be faster.
258 // The backward transforms of several fields can be batched, resulting in a
259 // single MPI exchange per MPI reshape instead of @c n_fields exchanges,
260 // but messages are @c n_fields times larger. Whether this pays off
261 // depends on the MPI transport (e.g. larger messages can switch from the
262 // eager to the rendezvous protocol), so this is measured as well, jointly
263 // with the decomposition.
264 if constexpr (Architecture == Arch::CPU) {
265 auto const seed = heffte::mpi::gather_boxes(*in_box, *out_box, comm);
266 auto const pencils = make_candidate(seed, true);
267 auto const slabs = make_candidate(seed, false);
268 struct Layout {
269 std::unique_ptr<FFT3D> fft;
270 Box box;
271 bool use_pencils;
272 bool batchable;
273 bool simd_veto;
274 };
275 auto const make_layout = [&](Box const &obox, bool pencils) -> Layout {
276 auto opts = options;
277 opts.use_pencils = pencils;
278 auto fft = make_fft3d(obox, opts);
279 auto const is_local_buffer_even = obox.count() % 2ll == 0ll;
280 auto const batchable =
281 (n_fields > 1u) and
282 boost::mpi::all_reduce(comm, is_local_buffer_even,
283 std::logical_and<bool>());
284 auto const local_simd_veto =
285 std::is_same_v<FloatType, float> and
286 (not is_local_buffer_even or fft->size_comm_buffers() % 2u == 1u);
287 auto const simd_veto = boost::mpi::all_reduce(comm, local_simd_veto,
288 std::logical_or<bool>());
289 return {std::move(fft), obox, pencils, batchable, simd_veto};
290 };
291 std::vector<Layout> layouts;
292 layouts.reserve(2u);
293 layouts.emplace_back(make_layout(pencils.out_boxes[this_rank], true));
294 // slab decomposition only works with column-major data in C2C 2D FFT
295 // https://github.com/icl-utk-edu/heffte/issues/93
296 if ((FFTConfig::use_r2c or
297 (FFTConfig::r_space_order == Utils::MemoryOrder::COLUMN_MAJOR and
298 FFTConfig::k_space_order == Utils::MemoryOrder::COLUMN_MAJOR)) and
299 slabs.valid and slabs.n_mpi_reshapes < pencils.n_mpi_reshapes) {
300 layouts.emplace_back(make_layout(slabs.out_boxes[this_rank], false));
301 }
302 auto *best_layout = &layouts.front();
303 auto best_batched = false;
304 if (layouts.size() >= 2ul or layouts[0].batchable) {
305 auto constexpr n_rounds = 3u;
306 auto constexpr n_steps = 5u;
307 auto best_time = std::numeric_limits<double>::max();
308 for (auto &layout : layouts) {
309 if (layout.simd_veto) {
310 // skip candidates with memory alignment issues
311 continue;
312 }
313 auto const batch_modes = layout.batchable
314 ? std::vector<bool>{false, true}
315 : std::vector<bool>{false};
316 for (bool const batched : batch_modes) {
317 auto min_time = std::numeric_limits<double>::max();
318 for (auto round = 0u; round < n_rounds; ++round) {
319 auto cur_time =
320 time_fft_step(*layout.fft, comm, n_fields, batched, n_steps);
321 if (batched) {
322 // batched FFT runtimes are skewed by the MPI barrier;
323 // account for MPI load imbalance with a small penalty
324 cur_time *= (comm.size() > 4) ? 1.25 : 1.1;
325 }
326 min_time = std::min(min_time, cur_time);
327 }
328 if (min_time < best_time) {
329 best_time = min_time;
330 best_layout = &layout;
331 best_batched = batched;
332 }
333 }
334 }
335 }
336 if (best_layout->simd_veto) {
337 throw p3m_tuning_exception("cannot align memory for SIMD");
338 }
339 options.use_pencils = best_layout->use_pencils;
340 out_box = std::make_unique<Box>(best_layout->box);
341 fft3d = std::move(best_layout->fft);
342 use_batched_fft = best_batched;
343 }
344 if constexpr (Architecture == Arch::CUDA) {
345 options.use_gpu_aware = ::communication_environment->is_mpi_gpu_aware();
346 }
347#ifdef ESPRESSO_FPE
348 // cuFFT builds device kernels using CUDA-JIT
349 // (https://docs.nvidia.com/cuda/archive/13.1.1/cufft/#plan-initialization-time)
350 // but this operation is not guaranteed to succeed for all mesh sizes,
351 // and in rare cases, it can send the SIGFPE signal
352 auto const trap_pause = (Architecture == Arch::CUDA)
354 : nullptr;
355#endif
356
357 if (not fft3d) {
358 fft3d = make_fft3d(*out_box, options);
359 // warm-up: FFTW plans are created on first use
360 time_fft_step(*fft3d, comm, 1, false, 0u);
361 }
362 m_workspace = decltype(m_workspace)((use_batched_fft ? n_fields : 1u) *
363 fft3d->size_workspace());
364 // MPI communicator is needed to destroy the FFT plans
365 m_mpi_env_lock = ::communication_environment->get_mpi_env();
366 }
367
369 return Utils::Vector3i(out_box->low);
370 }
372 return Utils::Vector3i(out_box->high) + Utils::Vector3i::broadcast(1);
373 }
378 return Utils::Vector3i(in_box->high) + Utils::Vector3i::broadcast(1) -
379 Utils::Vector3i(in_box->low);
380 }
381 void forward(auto &&in, auto &&out) {
382 fft3d->forward(in, out, m_workspace.data());
383 }
384 void backward(auto &&in, auto &&out) {
385 fft3d->backward(in, out, m_workspace.data());
386 }
387 /**
388 * Backward transform of @p n fields stored back to back, batched
389 * or one by one, whichever was measured to be faster.
390 */
391 void backward_batch(unsigned const n, auto *const in, auto *const out) {
392 if (use_batched_fft) {
393 assert(n <= m_batch_size);
394 fft3d->backward(static_cast<int>(n), in, out, m_workspace.data());
395 } else {
396 auto const ks_size = fft3d->size_outbox();
397 auto const rs_size = fft3d->size_inbox();
398 for (auto i = 0u; i < n; ++i) {
399 fft3d->backward(in + i * ks_size, out + i * rs_size,
400 m_workspace.data());
401 }
402 }
403 }
404};
405
406/**
407 * @brief heFFTe-backed implementation of the P3M FFT interface.
408 *
409 * Thin adapter that exposes @ref P3MFFT through the @ref P3MFFTBackend
410 * virtual interface, so the solver can hold it interchangeably with other
411 * backends. This is the general backend, used for any rank count.
412 */
413template <typename FloatType, class FFTConfig>
414struct P3MFFTHeffte final : public P3MFFTBackend<FloatType, FFTConfig> {
418
419 P3MFFTHeffte(boost::mpi::communicator comm,
420 Utils::Vector3i const &global_mesh,
421 Utils::Vector3i const &rs_local_ld_index,
422 Utils::Vector3i const &rs_local_ur_index,
423 Utils::Vector3i const &node_grid, unsigned n_fields = 1)
424 : m_impl(nullptr, comm, global_mesh, rs_local_ld_index, rs_local_ur_index,
425 node_grid, n_fields),
426 m_input(static_cast<std::size_t>(Utils::product(rs_local_size()))) {}
427
429 return m_impl.ks_local_ld_index();
430 }
432 return m_impl.ks_local_ur_index();
433 }
435 return m_impl.ks_local_size();
436 }
438 return m_impl.rs_local_size();
439 }
440 RSpaceScalar *forward_input_buffer() override { return m_input.data(); }
441 void forward(RSpaceScalar const *in, ComplexType *out) override {
442 m_impl.forward(in, out);
443 }
444 void backward(ComplexType *in, RSpaceScalar *out) override {
445 // heFFTe preserves the input; the non-const parameter is the interface's
446 // contract for backends that cannot (see P3MFFTBackend::backward).
447 m_impl.backward(in, out);
448 }
449 void backward_batch(unsigned const n, ComplexType *const in,
450 RSpaceScalar *const out) override {
451 m_impl.backward_batch(n, in, out);
452 }
453
454private:
457};
Vector implementation and trait types for boost qvm interoperability.
FFT manager.
Definition P3MFFT.hpp:53
void backward(auto &&in, auto &&out)
Definition P3MFFT.hpp:384
Utils::Vector3i ks_local_size() const
Definition P3MFFT.hpp:374
void forward(auto &&in, auto &&out)
Definition P3MFFT.hpp:381
P3MFFT(stream_type gpu_stream, boost::mpi::communicator comm, Utils::Vector3i const &global_mesh, Utils::Vector3i const &rs_local_ld_index, Utils::Vector3i const &rs_local_ur_index, Utils::Vector3i const &node_grid, unsigned n_fields=1u)
Definition P3MFFT.hpp:145
Utils::Vector3i ks_local_ur_index() const
Definition P3MFFT.hpp:371
Utils::Vector3i rs_local_size() const
Definition P3MFFT.hpp:377
~P3MFFT()
Definition P3MFFT.hpp:141
typename heffte::fft_output< FloatType >::type OutputType
Definition P3MFFT.hpp:55
void backward_batch(unsigned const n, auto *const in, auto *const out)
Backward transform of n fields stored back to back, batched or one by one, whichever was measured to ...
Definition P3MFFT.hpp:391
std::conditional_t< Architecture==Arch::CPU, heffte::backend::fftw, heffte::backend::cufft > backend
Definition P3MFFT.hpp:56
Utils::Vector3i ks_local_ld_index() const
Definition P3MFFT.hpp:368
std::conditional_t< Architecture==Arch::CPU, fft::vector< T >, typename heffte::fft3d< backend >::template buffer_container< T > > buffer_container
Definition P3MFFT.hpp:60
static DEVICE_QUALIFIER constexpr Vector< int, N > broadcast(typename Base::value_type const &value) noexcept
Definition Vector.hpp:144
static std::shared_ptr< scoped_pause > make_shared_pause_scoped()
Generate a shared handle to temporarily disable any currently active exception trap for the lifetime ...
Definition fe_trap.cpp:144
std::unique_ptr< CommunicationEnvironment > communication_environment
T product(Vector< T, N > const &v)
Definition Vector.hpp:379
VectorXi< 3 > Vector3i
Definition Vector.hpp:216
Definition fft.cpp:77
std::vector< T, allocator< T > > vector
Definition vector.hpp:54
STL namespace.
Common functions for dipolar and charge P3M.
Abstract interface for the P3M reciprocal-space FFT.
std::complex< FloatType > ComplexType
FloatType RSpaceScalar
Real-space scalar type.
Utils::Vector3i rs_local_size() const override
Definition P3MFFT.hpp:437
typename Base::RSpaceScalar RSpaceScalar
Definition P3MFFT.hpp:417
Utils::Vector3i ks_local_ld_index() const override
Definition P3MFFT.hpp:428
void forward(RSpaceScalar const *in, ComplexType *out) override
Definition P3MFFT.hpp:441
P3MFFTHeffte(boost::mpi::communicator comm, Utils::Vector3i const &global_mesh, Utils::Vector3i const &rs_local_ld_index, Utils::Vector3i const &rs_local_ur_index, Utils::Vector3i const &node_grid, unsigned n_fields=1)
Definition P3MFFT.hpp:419
Utils::Vector3i ks_local_size() const override
Definition P3MFFT.hpp:434
P3MFFTBackend< FloatType, FFTConfig > Base
Definition P3MFFT.hpp:415
RSpaceScalar * forward_input_buffer() override
Definition P3MFFT.hpp:440
Utils::Vector3i ks_local_ur_index() const override
Definition P3MFFT.hpp:431
void backward(ComplexType *in, RSpaceScalar *out) override
Definition P3MFFT.hpp:444
typename Base::ComplexType ComplexType
Definition P3MFFT.hpp:416
void backward_batch(unsigned const n, ComplexType *const in, RSpaceScalar *const out) override
Definition P3MFFT.hpp:449