Lattice Boltzmann method with MPI and CUDA

The lattice Boltzmann method (LBM) simulates a fluid with particle distributions on a regular grid. In this project I wrote 3 versions of a 2D solver for the flow past a cylinder: an optimised single-core version, a distributed version with MPI and a GPU version with CUDA. I measured how each of them scales and compared the results with the memory bandwidth of the hardware.

The code is on GitHub: https://github.com/chutommy/lattice-boltzmann

Method

The solver uses the D2Q9 lattice: a 2D grid where every cell holds 9 distributions \(f_i(\mathbf{x}, t)\), one for each discrete velocity \(\mathbf{c}_i\). There is 1 rest velocity, 4 along the axes and 4 along the diagonals.

The density \(\rho\) and the velocity \(\mathbf{u}\) of the fluid in a cell are sums over its distributions:

\[ \rho = \sum_{i=0}^{8} f_i, \qquad \rho\,\mathbf{u} = \sum_{i=0}^{8} \mathbf{c}_i f_i \]

A time step has 2 operations.

Collision: every cell relaxes towards its local equilibrium with a single relaxation time \(\tau\) (BGK).

\[ f_i^*(\mathbf{x}, t) = f_i(\mathbf{x}, t) - \frac{1}{\tau}\left[f_i(\mathbf{x}, t) - f_i^{eq}(\rho, \mathbf{u})\right] \]\[ f_i^{eq}(\rho, \mathbf{u}) = w_i\,\rho\left[1 + 3\,(\mathbf{c}_i \cdot \mathbf{u}) + \tfrac{9}{2}\,(\mathbf{c}_i \cdot \mathbf{u})^2 - \tfrac{3}{2}\,|\mathbf{u}|^2\right] \]

Streaming: the distributions after the collision move to the neighbouring cells along their velocities.

\[ f_i(\mathbf{x} + \mathbf{c}_i, t + 1) = f_i^*(\mathbf{x}, t) \]

Walls: in a solid cell, each pair of opposite distributions is swapped before streaming (bounce-back). A distribution that enters a solid cell returns to the cell it came from, which gives zero velocity at the surface (no-slip).

The relaxation time sets the kinematic viscosity \(\nu = c_s^2\,(\tau - \tfrac{1}{2})\), where \(c_s = 1/\sqrt{3}\) is the lattice speed of sound. The scheme is stable for \(\tau > 1/2\), and it approximates an incompressible flow only at a low Mach number \(u / c_s\).

Every update is local: a cell reads only itself and its 8 neighbours. The whole method is a stencil sweep over a regular grid, which is the property that the parallel versions rely on.

Flow past a cylinder

The domain is a channel of \(n_x \times n_y\) cells with a cylinder of diameter \(D\) inside. The top and bottom walls are no-slip. The inlet on the left sets a uniform velocity \(u_{in}\), and the outlet on the right copies the column before it. The Reynolds number is \(Re = u_{in} D / \nu\).

At \(Re \approx 100\) the wake behind the cylinder is unstable. Vortices are shed alternately from the two sides of the cylinder and form a Kármán vortex street. The shedding frequency \(f\) is reported as the Strouhal number \(St = f D / u_{in}\). For a cylinder at \(Re = 100\) the literature gives \(St \approx 0.16\).

The simulation below runs the same scheme on this page, on a 240×96 grid. The cylinder can be dragged. At \(Re = 40\) and below, the wake settles to a steady state. On this small grid the walls and the inlet are close to the cylinder, and the measured \(St\) at \(Re = 100\) is about 0.19. MLUPS is the throughput in million lattice updates per second, which is the metric used in the rest of this page.

All versions of the solver were validated on an 4000x2000 grid at \(Re = 100\) over 60,000 steps. Each of them measures \(St = 0.16\).

Serial baseline

Setup: a single core of an Intel Xeon Platinum 8360Y (2.4 GHz, 36 cores, 54 MB shared L3 [1]), with the node reserved exclusively. The grid is 4000×2000 and takes \(9 \cdot n_x n_y \cdot 8\,\text{B} \cdot 2 = 1.152\) GB. That is about 21 times the L3, so the data resides in DRAM. Each run does \(10^{10}\) cell updates.

Optimisation: the plain reference implementation reaches 22.1 MLUPS. It was optimised in stages.

The distributions are stored as a structure of arrays: 9 contiguous blocks of \(n_x n_y\) doubles, one per direction. The collide loop after these changes:

for (std::size_t k = 0; k < N; ++k) {
  double fi[Q];
  double rho = 0.0, mx = 0.0, my = 0.0;
  for (int i = 0; i < Q; ++i) {
    fi[i] = f[i * N + k];
    rho += fi[i];
    mx  += cx[i] * fi[i];
    my  += cy[i] * fi[i];
  }
  double ux = 0.0, uy = 0.0;
  if (rho > 0.0) {
    const double inv_rho = 1.0 / rho;
    ux = mx * inv_rho;
    uy = my * inv_rho;
  }
  const double u2 = ux * ux + uy * uy;

  for (int i = 0; i < Q; ++i) {
    const double cu  = cx[i] * ux + cy[i] * uy;
    const double feq = w[i] * rho * (1.0 + 3.0 * cu + 4.5 * cu * cu - 1.5 * u2);
    f[i * N + k] += -inv_tau * (fi[i] - feq);
  }

  if (solid[k]) {
    // Fullway bounce-back: in solid cells, swap each pair of opposite directions.
    std::swap(f[1 * N + k], f[3 * N + k]);
    std::swap(f[2 * N + k], f[4 * N + k]);
    std::swap(f[5 * N + k], f[7 * N + k]);
    std::swap(f[6 * N + k], f[8 * N + k]);
  }
}

The interior pass of stream has no bounds check:

for (int i = 0; i < Q; ++i) {
  for (std::size_t y = 1; y < ny_ - 1; ++y) {
    for (std::size_t x = 1; x < nx_ - 1; ++x) {
      const std::size_t sx = x - cx[i];
      const std::size_t sy = y - cy[i];
      ftmp[i * N + idx(x, y)] = f[i * N + idx(sx, sy)];
    }
  }
}

Profile: perf record attributes 69.91% of the samples to collide and bounce-back, 29.87% to stream, 0.15% to the boundary routines and 0.07% to the rest. In the MPI version the 2 sweeps and the boundary routines are all distributed across processes, so the parallel fraction is \(\alpha \approx 0.9993\).

DRAM roofline: a cell update moves \(4 \cdot 9 \cdot 8 = 288\) B. Collide reads and writes 9 doubles, and so does stream. The memory bandwidth of the socket is 204.8 GB/s [2], which limits the throughput of all 36 cores together.

\[ \text{MLUPS}_\text{ceil} = \frac{204.8\ \text{GB/s}}{288\ \text{B}} \approx 711\ \text{MLUPS} \]

The 29.8 MLUPS baseline is the DRAM throughput of a single core. 711 MLUPS is the limit of a socket, which is 19.75 MLUPS per core when all cores are busy. A node has 2 sockets, so its ceiling is 1422 MLUPS, and the ceiling grows linearly with the number of nodes.

The same calculation applies to the GPU and to the kernel variants described below.

MPI

The MPI version uses the optimised serial kernel (-march=native -flto, fused collide and bounce-back, __restrict__ pointers) and adds a communication layer.

2D decomposition: the grid is split by a 2D Cartesian topology. The remainder is distributed so that the tile sizes differ by at most 1 cell.

Block b;
b.nx    =  nx / dx + (cx < nx % dx ? 1 : 0);
b.ny    =  ny / dy + (cy < ny % dy ? 1 : 0);
b.x_off = (nx / dx) * cx + std::min(cx, nx % dx);
b.y_off = (ny / dy) * cy + std::min(cy, ny % dy);

Sparse halo exchange: each process has a halo of 1 cell on every side, plus 4 corner cells. Only the distributions that cross the interface are exchanged: 3 of 9 on an edge and 1 of 9 on a corner.

The edges are packed into one buffer per neighbour, and each corner is a single value:

// N edge
std::copy_n(&f_[fidx(2, 0L, long(ny_) - 1)], nx_, &buf_n_send_[0 * nx_]);
std::copy_n(&f_[fidx(5, 0L, long(ny_) - 1)], nx_, &buf_n_send_[1 * nx_]);
std::copy_n(&f_[fidx(6, 0L, long(ny_) - 1)], nx_, &buf_n_send_[2 * nx_]);
// ...
// PACK CORNERS
send_corner_[0] = f_[fidx(5, long(nx_) - 1, long(ny_) - 1)];  // NE
send_corner_[1] = f_[fidx(6, 0L,            long(ny_) - 1)];  // NW
send_corner_[2] = f_[fidx(8, long(nx_) - 1, 0L           )];  // SE
send_corner_[3] = f_[fidx(7, 0L,            0L           )];  // SW

MPI_Startall(16, sync_reqs_);

Persistent, non-blocking exchange: the 8 sends and 8 receives use persistent requests, which are created once and started at every step.

MPI_Send_init(buf_n_send_.data(), int(3 * nx_),  MPI_DOUBLE, neigh[N],  0, comm, &sync_reqs_[ 8]);
// ...
MPI_Send_init(&send_corner_[0], 1, MPI_DOUBLE, neigh[NE], 4, comm, &sync_reqs_[12]);
// ...
MPI_Recv_init(buf_n_recv_.data(), int(3 * nx_),  MPI_DOUBLE, neigh[S],  0, comm, &sync_reqs_[ 0]);
// ...
MPI_Recv_init(&recv_corner_[0], 1, MPI_DOUBLE, neigh[SW], 4, comm, &sync_reqs_[ 4]);

The interior is streamed while the messages are in transit. Only the perimeter pass waits for the halo.

collide_and_bounce_back();

// 1. Non-blocking 8-neighbour padding exchange.
// 2. Stream interior (in parallel).
// 3. Wait for padding-exchange to finish.
// 4. Stream boundary rows/columns.
post_sync_paddings();
stream_interior();
wait_sync_paddings();
stream_boundary();

Setup: nodes with 2 sockets of the Xeon 8360Y, 1 process per core, up to 8 nodes (576 processes). Each process does at least \(10^9\) cell updates, and every value is the median of 5 runs.

Strong scaling

Amdahl’s law: with \(\alpha \approx 0.9993\), \(S(P) = 1 / ((1 - \alpha) + \alpha / P)\) predicts the speedups \(S(72) \approx 69\), \(S(144) \approx 131\) and \(S(576) \approx 411\), with a limit of \(1 / (1 - \alpha) \approx 1429\). The measurements deviate from this prediction in both directions, because of bandwidth saturation and cache fit.

The first plot shows the speedup for 2:1 grids up to 16000×8000. The dotted red line is Amdahl’s prediction.

Strong scaling: speedup against the number of MPI processes, for 8 problem sizes

The second plot shows the same data as MLUPS per socket. The dashed red line is the DRAM roofline of a socket.

Strong scaling: MLUPS per socket against the number of MPI processes

The measurements fall into 3 regimes.

  1. Large grids (flat blue lines in the second plot) are bound by DRAM and stay below the bandwidth ceiling of a socket. A single socket reaches about 500 MLUPS, which is 70% of the 711 MLUPS roofline. Doubling the number of sockets doubles the total throughput, because every socket adds its own memory channels.
  2. Intermediate grids (rising blue lines) start bound by DRAM at 30 MLUPS for \(P = 1\) and slow down at \(P = 36\), like the large grids. As the tile of a process shrinks, it eventually fits in cache, and the throughput rises above the DRAM roofline. These grids exceed Amdahl’s prediction, and the 2000×1000 grid reaches a superlinear speedup at \(P = 288\).
  3. Small grids (grey) enter the cache one by one as \(P\) grows. Each curve leaves the DRAM-bound regime and continues at the rate of data that resides in cache. At high \(P\) the smallest grids slow down, and for the 2 smallest the halo communication dominates the work on the interior.

Weak scaling

Gustafson’s law: weak scaling fixes the tile of a process and grows the grid with \(P\), so the work and the halo size per process stay constant. With \(\alpha \approx 0.9993\), \(S(P) = 1 + (P - 1) \cdot \alpha\) predicts \(S(72) \approx 71.95\), \(S(144) \approx 143.90\) and \(S(576) \approx 575.60\), which is an efficiency of at least 99.9% at every \(P\). Like Amdahl’s law, this assumes a constant rate per process. The measurements show that the contention for the bandwidth of a socket breaks this assumption long before the serial fraction matters.

The plot shows the efficiency \(E(P) = \text{MLUPS}_\text{total} / (P \cdot \text{MLUPS}(1))\) for several fixed tiles. The dashed red line is the share of one process in the 711 MLUPS roofline, relative to the 29.8 MLUPS baseline: \((711 / 36) / 29.8 \approx 66\%\).

Weak scaling: efficiency against the number of MPI processes, for 6 tile sizes
  1. The 2 smallest tiles fit entirely in the L3. They start at the highest rates for a single process (67 and 35 MLUPS) and drop to an efficiency below 40%.
  2. The tiles bound by DRAM start near the 30 MLUPS baseline and all saturate at 47%.

The loss happens entirely within a socket. The plateau is reached at \(P = 36\), and the curves stay flat across multiple nodes. The DRAM plateau matches the bandwidth model: \(47 / 66 = 71\%\) of the ceiling, the same utilisation of the socket bandwidth as in strong scaling. The small tiles only appear less efficient because their baseline for a single process is higher. In absolute terms their rate per process is above that of the tiles bound by DRAM.

CUDA

Setup: a Tesla V100-PCIE-32GB.

Bandwidth ceiling: the V100 has 900 GB/s of HBM2 bandwidth [3]. The FP64 solver with 2 kernels moves the same 288 B per cell as the serial baseline, which gives a ceiling of \(900\ \text{GB/s} / 288\ \text{B} = 3125\) MLUPS. A single fused kernel halves the traffic to 144 B per cell (6250 MLUPS), and FP32 halves it again (12500 MLUPS). The compute limit of 7 TFLOPS is well above these memory ceilings, so the kernel is bound by memory.

Kernel layout: the structure follows the serial version. A collide and bounce-back kernel is followed by a stream kernel, and the host swaps the 2 buffers.

dim3 block(bx_, by_);
dim3 grid((int(nx_) + bx_ - 1) / bx_, (int(ny_) + by_ - 1) / by_);

collide_and_bounce_back_kernel<<<grid, block>>>(d_f, d_solid, nx, ny, inv_tau);
stream_kernel                 <<<grid, block>>>(d_f, d_ftmp, d_solid, nx, ny, u_in_);
std::swap(d_f, d_ftmp);

threadIdx.x runs along the rows, so a warp covers 32 contiguous cells. Every load and store of a direction is then fully coalesced, as long as blockDim.x is a multiple of 32.

const int x = blockIdx.x * blockDim.x + threadIdx.x;
const int y = blockIdx.y * blockDim.y + threadIdx.y;
if (x >= nx || y >= ny) return;

const size_t N = size_t(nx) * size_t(ny);
const size_t k = y * size_t(nx) + x;

The stream kernel pulls: a thread reads from its 9 neighbours and writes only to its own cell.

#pragma unroll 9
for (int i = 0; i < 9; ++i) {
  const int sx = x - d_cx[i];
  const int sy = y - d_cy[i];
  const size_t src = (sx >= 0 && sx < nx && sy >= 0 && sy < ny)
                     ? sy * size_t(nx) + sx : k;
  f_dst[i * N + k] = f_src[i * N + src];
}

Memory access: the lattice constants (\(c_x\), \(c_y\), \(w\)) are in constant memory.

__constant__ int    d_cx[9];
__constant__ int    d_cy[9];
__constant__ double d_w [9];

The solid mask never changes after the initialisation, and it is read with __ldg() through the read-only data cache.

// Fullway bounce-back: swap opposite pairs on solid cells.
if (__ldg(&solid[k])) {
  double t;
  t = fi[1];  fi[1]=fi[3];  fi[3] = t;
  t = fi[2];  fi[2]=fi[4];  fi[4] = t;
  t = fi[5];  fi[5]=fi[7];  fi[7] = t;
  t = fi[6];  fi[6]=fi[8];  fi[8] = t;
}

Block size

The plot shows the throughput of the FP64 build with 2 kernels for every block size on an 8000×4000 grid. The skipped combinations exceed the limit of 1024 threads per block.

MLUPS for block sizes from 4 by 1 to 512 by 2

Fused kernel and FP32

I measured 3 more builds: FP64 fused, FP32 with 2 kernels and FP32 fused.

The fused kernel merges collide, bounce-back and stream into a single kernel that pushes. Each thread loads only the \(f_i\) of its own cell, does the collision and the bounce-back swap in registers, and writes the results directly to the 9 neighbours in the second buffer.

// PUSH-based streaming.
#pragma unroll 9
for (int i = 0; i < 9; ++i) {
  const int tx = x + d_cx[i];
  const int ty = y + d_cy[i];
  if (tx >= 0 && tx < nx && ty >= 0 && ty < ny)
    f_dst[i * N + size_t(ty) * size_t(nx) + size_t(tx)] = fi[i];

  // PULL-based streaming for out-of-boundary components.
  const int sx = x - d_cx[i];
  const int sy = y - d_cy[i];
  if (sx < 0 || sx >= nx || sy < 0 || sy >= ny)
    f_dst[i * N + k] = fi[i];
}

A thread reads only data from before the step, so no synchronisation between collide and stream is needed. The intermediate read and write of the first buffer disappear, and the bytes per cell halve. FP32 halves them once more in either version.

Problem size

The plot shows all 4 builds on grids from 2 thousand to 33.6 million cells, with a block size of 64×16. The dashed lines are the bandwidth ceilings of the builds.

MLUPS of the 4 CUDA builds for grids from 64 by 32 to 8192 by 4096
  1. Kernel launch (up to 256×128): the grid has too few thread blocks to fill the SMs, and the wall time is dominated by the overhead of launching kernels.
  2. Cache (384×192 to 768×384): the FP32 build with 2 kernels is faster than the FP64 fused build. The stream pass is probably served mostly by cache and not by HBM, so the fused kernel has no advantage in traffic. The split into 2 kernels uses fewer registers per thread, and its pull writes are coalesced, while the fused kernel scatters its writes over 9 targets.
  3. HBM (from 1024×512): the working set no longer fits in cache, the builds are bound by bandwidth, and the lower traffic of the fused kernel shows. FP32 doubles the throughput once more. From 1536×768 on, all 4 builds are flat.

On the largest grid the builds reach 2653 MLUPS (FP64, 2 kernels), 4588 MLUPS (FP32, 2 kernels), 5023 MLUPS (FP64, fused) and 8584 MLUPS (FP32, fused). That is 85%, 73%, 80% and 69% of their ceilings.

References

  1. Intel. Intel Xeon Platinum 8360Y Processor, specifications.
  2. TechPowerUp. Intel Xeon Platinum 8360Y, specifications.
  3. NVIDIA. NVIDIA Tesla V100 GPU accelerator, datasheet.