Skip to main content

Productivity meets performance: benchmarking domain-decomposed stencils

Abstract: These days, with LLMs at our fingertips, writing code has become easy. Writing parallel code is relatively easy, too. But writing code that scales efficiently without bottlenecks is more challenging. Getting the best possible performance out of the available hardware is harder still.

In this webinar, we solve and benchmark a tightly coupled 3D numerical problem in C+MPI and Chapel, comparing their performance. We walk through the code optimization process, examining how performance scales with increasing problem sizes and numbers of nodes and CPU cores, while accounting for hardware limitations and bottlenecks. The goal is to demonstrate a workflow based on understanding performance and making informed decisions rather than simply throwing more hardware at the problem.

Workshop outline

Goals:

  • Show how to profile a tightly-coupled parallel application, resolving multiple bottlenecks. The full story could be quite complex.
  • Show that you cannot make any assumptions about (parallel) performance.
  • Compare Chapel’s performance with the more widely used C+MPI. When teaching Chapel, I usually focus on its parallel scaling, but there is much more to the story, enough to warrant a full webinar.

Plan:

  1. numerical 3D problem description
  2. walk through a parallel C+MPI implementation
  3. serial Chapel implementation
  4. shared-memory Chapel implementation
  5. distributed-memory Chapel implementation

We’ll do extensive benchmarking on a single CPU core, across multiple cores on the same node, and on up to four nodes on Fir.

Problem description

We’ll be solving numerically the 3D heat diffusion problem:

\[ \Large {\partial T(x,y,z,t)\over\partial t}= {\partial^2 T\over\partial x^2}+ {\partial^2 T\over\partial y^2}+ {\partial^2 T\over\partial z^2} \]

We discretize the solution \(T(x,y,z,t)\approx T^n_{i,j,k}\) with \(i=1..n_x\), \(j=1..n_y\), \(k=1..n_z\), and set the initial temperature at 25 degrees and apply the following constant boundary conditions:

  • x-sides: \(T^n_{0,1..n_y,1..n_z}\equiv 0\) on the left and \(T^n_{n_x+1,1..n_y,1..n_z}\equiv 80\) on the right
  • y-sides: \(T^n_{1..n_x,0,1..n_z}\equiv 0\) on the left and \(T^n_{1..n_x,n_y+1,1..n_z}\equiv 80\) on the right
  • z-sides: \(T^n_{1..n_x,1..n_y,0}\equiv 0\) on the left and \(T^n_{1..n_x,1..n_y,n_z+1}\equiv 80\) on the right

We discretize the equation with forward Euler time stepping:

\[ \large \begin{split} {T^{n+1}_{i,j,k}-T^n_{i,j,k}\over\Delta t}=& {T^n_{i+1,j,k}-2T^n_{i,j,k}+T^n_{i-1,j,k}\over(\Delta x)^2}\\ &+{T^n_{i,j+1,k}-2T^n_{i,j,k}+T^n_{i,j-1,k}\over(\Delta y)^2}\\ &+{T^n_{i,j,k+1}-2T^n_{i,j,k}+T^n_{i,j,k-1}\over(\Delta z)^2} \end{split} \]

and for simplicity we assume \(\Delta x=\Delta y=\Delta z=1\) and \(\Delta t=1/6\). Our finite difference equation then becomes

\[ \large T^{n+1}_{i,j,k}={1\over 6}\left[ T^n_{i+1,j,k}+T^n_{i-1,j,k}+ T^n_{i,j+1,k}+T^n_{i,j-1,k}+ T^n_{i,j,k+1}+T^n_{i,j,k-1} \right] \]

i.e. at each time iteration we’ll be computing the new temperature Tnew according to:

Tnew[i,j,k] = (T[i-1,j,k] + T[i+1,j,k] +
               T[i,j-1,k] + T[i,j+1,k] +
               T[i,j,k-1] + T[i,j,k+1]) / 6.0;

Traditional C+MPI

We start with the industry-standard tools: C and MPI. We decompose our 3D domain among the available processes:

Domain decomposition with MPI send/receive buffers. For simplicity, we show a 2D case.

MPI communication pattern at each timestep.

Here is a traditional implementation (let’s save it as threeDimensional.c):

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <mpi.h>

int main(int argc, char** argv) {
  int rank, size;
  MPI_Init(&argc, &argv);
  MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  MPI_Comm_size(MPI_COMM_WORLD, &size);

  int nx = 100, ny = nx, nz = nx, niter = 10000, nout = 100;
  double tolerance = 2e-3;

  int dims[3] = {0, 0, 0};          // MPI will decide on all 3 dimensions
  MPI_Dims_create(size, 3, dims);   // create a balanced 3D processor grid
  int d1 = dims[0], d2 = dims[1], d3 = dims[2];

  int periods[3] = {0, 0, 0};   // non-periodic boundaries
  MPI_Comm cart_comm;
  MPI_Cart_create(MPI_COMM_WORLD, 3, dims, periods, 1, &cart_comm);

  // translate a rank into 3D grid coordinates
  int coords[3];
  MPI_Cart_coords(cart_comm, rank, 3, coords);
  int rx = coords[0], ry = coords[1], rz = coords[2];

  // find 6 neighbouring ranks (evaluate to MPI_PROC_NULL=-2 outside the grid)
  int x_prev, x_next, y_prev, y_next, z_prev, z_next;
  MPI_Cart_shift(cart_comm, 0, 1, &x_prev, &x_next);
  MPI_Cart_shift(cart_comm, 1, 1, &y_prev, &y_next);
  MPI_Cart_shift(cart_comm, 2, 1, &z_prev, &z_next);

  // compute local dimensions distributing across ranks
  int localX = nx / d1, xRem = nx % d1;
  int myX = localX + (rx < xRem ? 1 : 0);
  int xStart = rx * localX + (rx < xRem ? rx : xRem) + 1; // 1-based global start

  int localY = ny / d2, yRem = ny % d2;
  int myY = localY + (ry < yRem ? 1 : 0);
  int yStart = ry * localY + (ry < yRem ? ry : yRem) + 1; // 1-based global start

  int localZ = nz / d3, zRem = nz % d3;
  int myZ = localZ + (rz < zRem ? 1 : 0);
  int zStart = rz * localZ + (rz < zRem ? rz : zRem) + 1; // 1-based global start

  // Allocate local T and Tnew arrays with ghost cells (+2 for padding)
  int totalSize = (myX + 2) * (myY + 2) * (myZ + 2);
  double *T = (double *)calloc(totalSize, sizeof(double));
  double *Tnew = (double *)calloc(totalSize, sizeof(double));

  // preprocessor macro translating a local 3D coordinate (i,j,k) into a local 1D linear index
#define IDX(i,j,k) ((k) * (myY + 2) * (myX + 2) + (j) * (myX + 2) + (i))

  for (int k = 1; k <= myZ; k++)
    for (int j = 1; j <= myY; j++)
      for (int i = 1; i <= myX; i++)
        T[IDX(i,j,k)] = 25.0; // initial temperature

  if (rx == d1 - 1) // if this rank owns the rightmost x-boundary
    for (int k = 1; k <= myZ; k++)
      for (int j = 1; j <= myY; j++)
        T[IDX(myX+1,j,k)] = 80.0;
  if (ry == d2 - 1) // if this rank owns the rightmost y-boundary
    for (int k = 1; k <= myZ; k++)
      for (int i = 1; i <= myX; i++)
        T[IDX(i,myY+1,k)] = 80.0;
  if (rz == d3 - 1) // if this rank owns the rightmost z-boundary
    for (int j = 1; j <= myY; j++)
      for (int i = 1; i <= myX; i++)
        T[IDX(i,j,myZ+1)] = 80.0;

  if (rank == 0)
    printf("Working with a 3D grid %ix%ix%i up to %i iterations or dT below %e\n", nx, ny, nz, niter, tolerance);

  // Allocate communication buffers for 6 faces
  int faceYZ = myY * myZ;
  int faceXZ = myX * myZ;
  int faceXY = myX * myY;

  double *sendXPrev = (double *)malloc(faceYZ * sizeof(double));
  double *recvXPrev = (double *)malloc(faceYZ * sizeof(double));
  double *sendXNext = (double *)malloc(faceYZ * sizeof(double));
  double *recvXNext = (double *)malloc(faceYZ * sizeof(double));

  double *sendYPrev = (double *)malloc(faceXZ * sizeof(double));
  double *recvYPrev = (double *)malloc(faceXZ * sizeof(double));
  double *sendYNext = (double *)malloc(faceXZ * sizeof(double));
  double *recvYNext = (double *)malloc(faceXZ * sizeof(double));

  double *sendZPrev = (double *)malloc(faceXY * sizeof(double));
  double *recvZPrev = (double *)malloc(faceXY * sizeof(double));
  double *sendZNext = (double *)malloc(faceXY * sizeof(double));
  double *recvZNext = (double *)malloc(faceXY * sizeof(double));

  double delta = tolerance * 10.0;
  int count = 0;
  double start_time = MPI_Wtime();

  while (count < niter && delta >= tolerance) {
    count++;

    // x-direction halo exchange
    int idx = 0;
    for (int k = 1; k <= myZ; k++) {
      for (int j = 1; j <= myY; j++) {
        sendXPrev[idx] = T[IDX(1,j,k)];
        sendXNext[idx] = T[IDX(myX,j,k)];
        idx++;
      }
    }
    // info flows to smaller x: send to smaller x and receive from higher x
    MPI_Sendrecv(sendXPrev, faceYZ, MPI_DOUBLE, x_prev, 0, recvXNext, faceYZ,
         MPI_DOUBLE, x_next, 0, cart_comm, MPI_STATUS_IGNORE);
    // info flows to higher x: send to higher x and receive from smaller x
    MPI_Sendrecv(sendXNext, faceYZ, MPI_DOUBLE, x_next, 1, recvXPrev, faceYZ,
         MPI_DOUBLE, x_prev, 1, cart_comm, MPI_STATUS_IGNORE);
    idx = 0;
    if (x_prev != MPI_PROC_NULL) {
      for (int k = 1; k <= myZ; k++) {
        for (int j = 1; j <= myY; j++) {
          T[IDX(0,j,k)] = recvXPrev[idx++];
        }
      }
    }
    idx = 0;
    if (x_next != MPI_PROC_NULL) {
      for (int k = 1; k <= myZ; k++) {
        for (int j = 1; j <= myY; j++) {
          T[IDX(myX+1,j,k)] = recvXNext[idx++];
        }
      }
    }

    // y-direction halo exchange
    idx = 0;
    for (int k = 1; k <= myZ; k++) {
      for (int i = 1; i <= myX; i++) {
        sendYPrev[idx] = T[IDX(i,1,k)];
        sendYNext[idx] = T[IDX(i,myY,k)];
        idx++;
      }
    }
    MPI_Sendrecv(sendYPrev, faceXZ, MPI_DOUBLE, y_prev, 2, recvYNext, faceXZ,
         MPI_DOUBLE, y_next, 2, cart_comm, MPI_STATUS_IGNORE);
    MPI_Sendrecv(sendYNext, faceXZ, MPI_DOUBLE, y_next, 3, recvYPrev, faceXZ,
         MPI_DOUBLE, y_prev, 3, cart_comm, MPI_STATUS_IGNORE);
    idx = 0;
    if (y_prev != MPI_PROC_NULL) {
      for (int k = 1; k <= myZ; k++) {
        for (int i = 1; i <= myX; i++) {
          T[IDX(i,0,k)] = recvYPrev[idx++];
        }
      }
    }
    idx = 0;
    if (y_next != MPI_PROC_NULL) {
      for (int k = 1; k <= myZ; k++) {
        for (int i = 1; i <= myX; i++) {
          T[IDX(i,myY+1,k)] = recvYNext[idx++];
        }
      }
    }

    // z-direction halo exchange
    idx = 0;
    for (int j = 1; j <= myY; j++) {
      for (int i = 1; i <= myX; i++) {
        sendZPrev[idx] = T[IDX(i,j,1)];
        sendZNext[idx] = T[IDX(i,j,myZ)];
        idx++;
      }
    }
    MPI_Sendrecv(sendZPrev, faceXY, MPI_DOUBLE, z_prev, 4, recvZNext, faceXY,
         MPI_DOUBLE, z_next, 4, cart_comm, MPI_STATUS_IGNORE);
    MPI_Sendrecv(sendZNext, faceXY, MPI_DOUBLE, z_next, 5, recvZPrev, faceXY,
         MPI_DOUBLE, z_prev, 5, cart_comm, MPI_STATUS_IGNORE);
    idx = 0;
    if (z_prev != MPI_PROC_NULL) {
      for (int j = 1; j <= myY; j++) {
        for (int i = 1; i <= myX; i++) {
          T[IDX(i,j,0)] = recvZPrev[idx++];
        }
      }
    }
    idx = 0;
    if (z_next != MPI_PROC_NULL) {
      for (int j = 1; j <= myY; j++) {
        for (int i = 1; i <= myX; i++) {
          T[IDX(i,j,myZ+1)] = recvZNext[idx++];
        }
      }
    }
    // stencil computation
    double localDelta = 0.0;
    for (int k = 1; k <= myZ; k++) {
      for (int j = 1; j <= myY; j++) {
        for (int i = 1; i <= myX; i++) {
          Tnew[IDX(i,j,k)] = (T[IDX(i-1,j,k)] + T[IDX(i+1,j,k)] +
                  T[IDX(i,j-1,k)] + T[IDX(i,j+1,k)] +
                  T[IDX(i,j,k-1)] + T[IDX(i,j,k+1)]) / 6.0;
          double diff = fabs(Tnew[IDX(i,j,k)] - T[IDX(i,j,k)]);
          if (diff > localDelta) {
            localDelta = diff;
          }
        }
      }
    }
    MPI_Allreduce(&localDelta, &delta, 1, MPI_DOUBLE, MPI_MAX, cart_comm);
    // update T = Tnew
    for (int k = 1; k <= myZ; k++)
      for (int j = 1; j <= myY; j++)
        for (int i = 1; i <= myX; i++)
          T[IDX(i,j,k)] = Tnew[IDX(i,j,k)];
    if (count % nout == 0 && rank == 0) {
      printf("Iteration %i: delta=%f T=%f\n", count, delta, T[IDX(1,1,1)]);
    }
  }
  double elapsed = MPI_Wtime() - start_time;
  if (rank == 0) {
    printf("At %ix%ix%i after %i iterations: delta=%e in %f sec, running at %d stencils/s\n", 
           nx, ny, nz, count, delta, elapsed, (int)((double)nx*ny*nz*count/elapsed));
  }

  free(T); free(Tnew);
  free(sendXPrev); free(recvXPrev);
  free(sendXNext); free(recvXNext);
  free(sendYPrev); free(recvYPrev);
  free(sendYNext); free(recvYNext);
  free(sendZPrev); free(recvZPrev);
  free(sendZNext); free(recvZNext);
  MPI_Comm_free(&cart_comm);
  MPI_Finalize();
  return 0;
}
NoteMeasuring performance

The total runtime of this code would not a good measure of its performance: how do we compare two runs with different grid resolutions, different numbers of time steps, or different convergence criteria? We want our performance measure to be invariant to these variations.

For performance measurement, instead of the elapsed time, let’s record the number of stencils computed per second. As we throw more hardware at the problem, this number should scale up linearly if all goes well. Similarly, it should stay constant on a fixed set of CPU cores, independently of the grid size, or the number of timesteps, and ideally of the programming language.

Let’s run this code on a cluster:

cd stencil
mpicc -O2 threeDimensional.c -o threeDimensional
srun --unbuffered --time=2:0:0 --mem-per-cpu=3600 ./threeDimensional
seff <jobID>   # check memory usage, should fit under 3600MB

Play with different grid resolutions in serial until convergence:

At 30^3 after 852 iterations: delta=1.995233e-03 in 0.038583 sec, running at 596,213,685 stencils/s
At 50^3 after 1791 iterations: delta=1.999012e-03 in 0.365023 sec, running at 613,317,743 stencils/s
At 100^3 after 4499 iterations: delta=1.999374e-03 in 7.627444 sec, running at 589,843,720 stencils/s
At 500^3 after 12160 iterations: delta=1.999991e-03 in 3389.347329 sec, running at 448,463,923 stencils/s

We see roughly the same performance, although there is a drop at higher resolutions due to having to allocate and access larger arrays, and – maybe – due to failing SIMD vectorization (e.g. conditionals inside loops) for larger arrays. We’ll address the latter issue soon.

At a fixed resolution, play in serial with the number of steps:

At 500^3 after 10 iterations: delta=2.290586e+00 in 3.020025 sec, running at 413,903,849 stencils/s
At 500^3 after 100 iterations: delta=2.427930e-01 in 26.834820 sec, running at 465,812,696 stencils/s
At 500^3 after 1000 iterations: delta=2.431287e-02 in 293.506714 sec, running at 425,884,635 stencils/s
At 500^3 after 10000 iterations: delta=2.431879e-03 in 2754.711330 sec, running at 453,768,054 stencils/s

With more steps, the relative overhead of starting / stopping the calculation gets smaller, although there is some runtime variation.

Try parallel runs with --mem-per-cpu=3600 --nodes=4 --tasks-per-node=192, i.e. using 4 full Fir nodes (768 CPU cores):

cd ~/chapel/stencil && make clean
mpicc -O2 02-threeDimensional.c -o threeDimensional
sbatch runc-fir.sh

I could push my calculation up to \(5600^3\) resolution:

At  500^3 after 10 iterations: delta=2.290586e+00 in 0.071705 sec, running at 17,432,622,391 stencils/s
At 1000^3 after 10 iterations: delta=2.290586e+00 in 0.177971 sec, running at 56,188,836,835 stencils/s
At 1700^3 after 10 iterations: delta=2.290586e+00 in 0.739565 sec, running at 66,430,916,644 stencils/s
At 1800^3 after 10 iterations: delta=2.290586e+00 in 0.811869 sec, running at 71,834,253,899 stencils/s
At 1900^3 after 10 iterations: delta=2.290586e+00 in 1.023908 sec, running at 66,988,472,556 stencils/s
At 2000^3 after 10 iterations: delta=2.290586e+00 in 1.148938 sec, running at 69,629,527,283 stencils/s
At 3000^3 after 10 iterations: delta=2.290586e+00 in 3.780810 sec, running at 71,413,267,055 stencils/s
At 4000^3 after 10 iterations: delta=2.290586e+00 in 9.107106 sec, running at 70,274,795,004 stencils/s
At 5000^3 after 10 iterations: delta=2.290586e+00 in 18.301174 sec, running at 68,301,629,472 stencils/s
At 5200^3 after 10 iterations: delta=2.290586e+00 in 20.790127 sec, running at 67,632,101,141 stencils/s
At 5400^3 after 10 iterations: delta=2.290586e+00 in 23.461213 sec, running at 67,116,733,435 stencils/s
At 5600^3 after 10 iterations: delta=2.290586e+00 in 26.312814 sec, running at 66,741,626,146 stencils/s
Memory Efficiency: 74.53% of 2.93 TB (750.00 GB/node)

This makes sense: at \(5600^3\) we allocate two large (T, Tnew) double-precision arrays, which would take \(5600^3*8*2/(1024^2*768)\approx 3489\)MB per core, not counting the MPI buffers and other smaller variables.

On 768 CPU cores the calculation ran ~147X faster than in serial, i.e. there is a significant overhead with MPI communication in this tightly coupled problem. Considering that our C+MPI code has been tested a lot and uses industry-standard techniques for 3D domain decomposition and ghost zone communication, we’ll treat these latest runs as a gold reference when benchmarking other implementations.

Serial Chapel

Next, we’ll write the same code in serial Chapel which is the most popular of the PGAS (Partitioned Global Address Space) family languages. These languages provide a global view of memory while supporting data and computation distributed across multiple nodes (locales) on a cluster.

We’ll start with the serial code because we can optimize it before parallelizing.

Here is our serial implementation (save it as serial.chpl):

use Time;

config const nx = 500, ny = nx, nz = nx, niter = 10, nout = 10, tolerance = 0.002;
var count = 0: int;

writef('Working with %ix%ix%i to %i iterations or dT below %r\n', nx, ny, nz, niter, tolerance);

var T, Tnew: [0..nx+1,0..ny+1,0..nz+1] real;
T[1..nx,1..ny,1..nz] = 25;                         // initial temperature
for (j,k) in {1..ny,1..nz} {   // rightmost x-boundary
  T[nx+1,j,k] = 80.0;
  Tnew[nx+1,j,k] = T[nx+1,j,k];
}
for (i,k) in {1..nx,1..nz} {   // rightmost y-boundary
  T[i,ny+1,k] = 80.0;
  Tnew[i,ny+1,k] = T[i,ny+1,k];
}
for (i,j) in {1..nx,1..ny} {   // rightmost z-boundary
  T[i,j,nz+1] = 80.0;
  Tnew[i,j,nz+1] = T[i,j,nz+1];
}

writef('Iteration 0: T=%r\n', T[1,1,1]);
var delta = tolerance*10;    // some safe initial large value
var watch: stopwatch;
watch.start();
while (count < niter && delta >= tolerance) {
  count += 1;
  delta = 0;
  for (i,j,k) in {1..nx,1..ny,1..nz} {
    Tnew[i,j,k] = (T[i-1,j,k] + T[i+1,j,k] + T[i,j-1,k] + T[i,j+1,k] + T[i,j,k-1] + T[i,j,k+1]) / 6.0;
  }
  delta = max reduce [(i,j,k) in {1..nx,1..ny,1..nz}] abs(Tnew[i,j,k] - T[i,j,k]);
  T[1..nx,1..ny,1..nz] = Tnew[1..nx,1..ny,1..nz];
  if count%nout == 0 then writef('Iteration %i: delta=%r T=%r\n', count, delta, T[1,1,1]);
}
watch.stop();
writef('At %ix%ix%i after %i iterations: delta=%r in %r sec, running at %i stencils/s\n',
       nx, ny, nz, count, delta, watch.elapsed(), ((nx:real*ny*nz*count)/watch.elapsed()): int);

Let’s compile it with a single-locale Chapel compiler:

# module load chapel-multicore/2.4.0
source ~/startSingleLocale.sh   # most recent 2.10.0 version
chpl --fast serial.chpl
srun --unbuffered --time=1:0:0 --mem-per-cpu=3600 ./serial --nx=30 --niter=15000 --nout=500
...

Similar to C+MPI, we’ll start by trying different grid resolutions until the results converge:

Chapel:
At 30^3 after 852 iterations: delta=0.00199523 in 0.031834 sec, running at 722,623,609 stencils/s
At 50^3 after 1791 iterations: delta=0.00199901 in 0.311114 sec, running at 719,591,532 stencils/s
At 100^3 after 4499 iterations: delta=0.00199937 in 6.6164 sec, running at 679,977,437 stencils/s
At 500^3 after 12160 iterations: delta=0.00199999 in 5096.24 sec, running at 298,259,080 stencils/s

We get the same numerical solution as in C+MPI for the fixed tolerance, converging after the same number of timesteps. Similar to C+MPI, at progressively higher resolutions our code runs slower, but with Chapel the effect is more pronounced.

Max reduction

Let’s take a look at the line:

  delta = max reduce [(i,j,k) in {1..nx,1..ny,1..nz}] abs(Tnew[i,j,k] - T[i,j,k]);

Here we are going through all grid points, compute the difference between the old and the new solutions, and of these pick a single result using a max reduction operator. Effectively, this will allocate an array of differences and pick the largest value.

Alternatively, we could rewrite this as:

    var tmp = abs(Tnew[i,j,k]-T[i,j,k]);
    if tmp > delta then delta = tmp;

inside the mesh loop immediately after computing the stencil Tnew[i,j,k]. This will act on scalar values, avoiding building an intermediate array. On the other hand, this approach introduces a conditional statement into the mesh loop that might prevent SIMD vectorization.

We could also introduce a second loop and try to use the max function on scalar values:

  for (i,j,k) in {1..nx,1..ny,1..nz} {
    delta = max(delta, abs(Tnew[i,j,k] - T[i,j,k]));
  }

Which of the three approaches works best depends on the compiler details, cache size, and processor architecture; it’s impossible to know without testing.

On Fir, with a Chapel build using the gcc/12.3 compiler the winner is (though I’ve seen different results on other machines):

    var tmp = abs(Tnew[i,j,k]-T[i,j,k]);
    if tmp > delta then delta = tmp;

Array assignment

After we compute delta, we need to assign the newly computed temperatures to T:

  T[1..nx,1..ny,1..nz] = Tnew[1..nx,1..ny,1..nz];

The issue here is that we assign array subsections T[1..nx,1..ny,1..nz] = Tnew[1..nx,1..ny,1..nz], instead of assigning the whole arrays. This hurts performance.

Since our boundary conditions were coded exactly the same for T and Tnew, and we never update those boundary values inside the iteration loop, we can simply replace this line with T = Tnew, or even better do the array swap T <=> Tnew.

Faster code

Here is the new serial code serial.chpl:

use Time;

config const nx = 500, ny = nx, nz = nx, niter = 10, nout = 10, tolerance = 0.002;
var count = 0: int;

writef('Working with %ix%ix%i to %i iterations or dT below %r\n', nx, ny, nz, niter, tolerance);

var T, Tnew: [0..nx+1,0..ny+1,0..nz+1] real;
T[1..nx,1..ny,1..nz] = 25;                         // initial temperature
for (j,k) in {1..ny,1..nz} {   // rightmost x-boundary
  T[nx+1,j,k] = 80.0;
  Tnew[nx+1,j,k] = T[nx+1,j,k];
}
for (i,k) in {1..nx,1..nz} {   // rightmost y-boundary
  T[i,ny+1,k] = 80.0;
  Tnew[i,ny+1,k] = T[i,ny+1,k];
}
for (i,j) in {1..nx,1..ny} {   // rightmost z-boundary
  T[i,j,nz+1] = 80.0;
  Tnew[i,j,nz+1] = T[i,j,nz+1];
}

writef('Iteration 0: T=%r\n', T[1,1,1]);
var delta = tolerance*10;    // some safe initial large value
var watch: stopwatch;
watch.start();
while (count < niter && delta >= tolerance) {
  count += 1;
  delta = 0;
  for (i,j,k) in {1..nx,1..ny,1..nz} {
    Tnew[i,j,k] = (T[i-1,j,k] + T[i+1,j,k] + T[i,j-1,k] + T[i,j+1,k] + T[i,j,k-1] + T[i,j,k+1]) / 6.0;
    var tmp = abs(Tnew[i,j,k]-T[i,j,k]);
    if tmp > delta then delta = tmp;
  }
  T <=> Tnew;
  if count%nout == 0 then writef('Iteration %i: delta=%r T=%r\n', count, delta, T[1,1,1]);
}
watch.stop();
writef('At %ix%ix%i after %i iterations: delta=%r in %r sec, running at %i stencils/s\n',
       nx, ny, nz, count, delta, watch.elapsed(), ((nx:real*ny*nz*count)/watch.elapsed()): int);

After rerunning the serial code for 300 iterations, the two versions show drastically different times:

# initial version
At 500^3 after 300 iterations: delta=0.0810363 in 130.988 sec, running at 286,285,591 stencils/s

# improved version
At 500^3 after 300 iterations: delta=0.0810363 in 45.37 sec, running at 826,537,450 stencils/s
Note

To ensure the runs use the same node, all one-to-one comparisons in these notes were performed within the same Slurm job.

ImportantKey points
  1. Avoid allocating large temporary arrays. Instead, run for loops, use array assignment or array swap.
  2. Aim for SIMD vectorization where possible; check if conditionals inside large loops hurt your performance.
  3. By default, for array storage, similar to C, Chapel uses row-major order (the last index varies fastest). However, it also provides high-level abstractions that help you write clean, layout-aware code without getting bogged down in such details, e.g. iterate over the domain for (i, j, k) in A.domain do A[i,j,k]=... or provide the domain explicitly.

Shared-memory code

We convert the serial code to a multithreaded version by changing just one line:

<   delta = 0;
<   for (i,j,k) in {1..nx,1..ny,1..nz} {
---
>   forall (i,j,k) in {1..nx,1..ny,1..nz} with (max reduce delta) {

and save the parallel version as singleLocale.chpl.

Single-locale compiler

First, we try the same single-locale compiler:

source ~/startSingleLocale.sh
chpl --fast singleLocale.chpl -o shared

srun --unbuffered --time=1:0:0 --mem-per-cpu=3600 --account=... ./shared --nx=500 --niter=300 --nout=50
At 500^3 after 300 iterations: delta=0.0810363 in 43.1899 sec, running at 868,259,455 stencils/s

srun --unbuffered --time=1:0:0 --cpus-per-task=8 --mem-per-cpu=3600 --account=... ./shared --nx=500 --niter=300 --nout=50
At 500^3 after 300 iterations: delta=0.0810363 in 5.94851 sec, running at 6,304,099,682 stencils/s

srun --unbuffered --time=1:0:0 --cpus-per-task=32 --mem-per-cpu=3600 --account=... ./shared --nx=500 --niter=300 --nout=50
At 500^3 after 300 iterations: delta=0.0810363 in 2.19937 sec, running at 17,050,313,884 stencils/s

srun --unbuffered --time=1:0:0 --cpus-per-task=192 --mem=0 --account=... ./shared --nx=500 --niter=300 --nout=50
At 500^3 after 300 iterations: delta=0.0810363 in 1.20958 sec, running at 31,002,471,103 stencils/s
Memory Efficiency: 0.27% of 750.00 GB (750.00 GB/node)

Our parallel scaling is excellent! However, our memory usage is terrible … let’s try to scale up to \(3500^3\) – at this resolution we should be using most of the node’s memory:

srun --unbuffered --time=1:0:0 --cpus-per-task=192 --mem=0 --account=... ./shared --nx=3500 --niter=100 --nout=10
srun: job 6989610 queued and waiting for resources
At 3500^3 after 100 iterations: delta=0.242793 in 171.399 sec, running at 25,014,746,594 stencils/s
CPU Efficiency: 88.89% of 10:52:48 core-walltime
Memory Efficiency: 85.51% of 750.00 GB (750.00 GB/node)

Multi-locale compiler

Distributed-memory code

BlockDist

Next, we check the distributed-memory version of the code that uses BlockDist.

In Chapel, BlockDist is a standard distributed map that partitions a dense domain into contiguous blocks across a set of nodes (locales). Rather than forcing you to manually manage rank/size arithmetic, explicit send/receive buffers, or global-to-local index translation, like we did in C+MPI, BlockDist ties index ownership and forall task placement directly to the domain and array abstractions.

Here are the changes to singleLocale.chpl to make it distributed:

< use Time;
---
> use Time, BlockDist;

< var T, Tnew: [0..nx+1,0..ny+1,0..nz+1] real;
---
> const largerMesh: domain(3) dmapped new blockDist(boundingBox={1..nx, 1..ny, 1..nz}) = {0..nx+1, 0..ny+1, 0..nz+1};
> var T, Tnew: [largerMesh] real;   // a block-distributed array of temperatures

BlockDist in 2D.
  • BlockDist allocates the exact size for the subdomain on each locale
  • it caches communication

Here is the complete distributed-memory code (contains a deliberate error, save it as block.chpl):

use Time, BlockDist;

config const nx = 500, ny = nx, nz = nx, niter = 10, nout = 10, tolerance = 0.002;
var count = 0: int;

writef('Working with %ix%ix%i to %i iterations or dT below %r\n', nx, ny, nz, niter, tolerance);

const largerMesh: domain(3) dmapped new blockDist(boundingBox={1..nx, 1..ny, 1..nz}) = {0..nx+1, 0..ny+1, 0..nz+1};
var T, Tnew: [largerMesh] real;   // a block-distributed array of temperatures
T[1..nx,1..ny,1..nz] = 25;     // initial temperature
for (j,k) in {1..ny,1..nz} {   // rightmost x-boundary
  T[nx+1,j,k] = 80.0;
  Tnew[nx+1,j,k] = T[nx+1,j,k];
}
for (i,k) in {1..nx,1..nz} {   // rightmost y-boundary
  T[i,ny+1,k] = 80.0;
  Tnew[i,ny+1,k] = T[i,ny+1,k];
}
for (i,j) in {1..nx,1..ny} {   // rightmost z-boundary
  T[i,j,nz+1] = 80.0;
  Tnew[i,j,nz+1] = T[i,j,nz+1];
}

writef('Iteration 0: T=%r\n', T[1,1,1]);
var delta = tolerance*10;   // some safe initial large value
var watch: stopwatch;
watch.start();
while (count < niter && delta >= tolerance) {
  count += 1;
  delta = 0;
  forall (i,j,k) in {1..nx,1..ny,1..nz} with (max reduce delta) {
    Tnew[i,j,k] = (T[i-1,j,k] + T[i+1,j,k] + T[i,j-1,k] + T[i,j+1,k] + T[i,j,k-1] + T[i,j,k+1]) / 6.0;
    var tmp = abs(Tnew[i,j,k]-T[i,j,k]);
    if tmp > delta then delta = tmp;
  }
  T <=> Tnew; // swap two arrays
  if count%nout == 0 then writef('Iteration %i: delta=%r T=%r\n', count, delta, T[1,1,1]);
}
watch.stop();
writef('At %ix%ix%i after %i iterations: delta=%r in %r sec, running at %i stencils/s\n',
       nx, ny, nz, count, delta, watch.elapsed(), ((nx:real*ny*nz*count)/watch.elapsed()): int);

Notice that all communication happens behind the scenes: we are not sending any messages explicitly.

Let’s compile and run it first on a single CPU core:

source ~/startMultiLocale.sh
make clean
chpl --fast block.chpl

# earlier run
# srun --unbuffered --time=1:0:0 --mem-per-cpu=3600 --account=... ./shared --nx=500 --niter=300 --nout=50
# At 500^3 after 300 iterations: delta=0.0810363 in 43.1899 sec, running at 868,259,455 stencils/s
srun --unbuffered --time=1:0:0 --mem-per-cpu=3600 --account=... ./block -nl 1 --nx=500 --niter=300 --nout=50
At 500^3 after 300 iterations: delta=0.0810363 in 598.24 sec, running at 62,683,891 stencils/s

That’s quite a drop in performance! I see a similar 12-15X drop on all machines when running the code on a single node, where the distributed arrays are effectively local, and there is no communication …. What’s causing this?

Short answer: indexing into global partitioned arrays adds a layer of abstraction: we need to determine which locale and local chunk own each index. For small problems, that adds quite a bit of overhead that should go away as we scale up the problem.

BlockDist benchmarking

Let’s hope that at scale we’ll get better performance compared to C+MPI!

Before we run the code at scale, let me point out a deliberate bug in the code. When computing the stencil, we wrote our forall mesh loop as:

  forall (i,j,k) in {1..nx,1..ny,1..nz} with (max reduce delta) {
    Tnew[i,j,k] = (T[i-1,j,k] + T[i+1,j,k] + T[i,j-1,k] + T[i,j+1,k] + T[i,j,k-1] + T[i,j,k+1]) / 6.0;
    var tmp = abs(Tnew[i,j,k]-T[i,j,k]);
    if tmp > delta then delta = tmp;
  }

Since the domain {1..nx,1..ny,1..nz} we are cycling over is local, the forall loop will split it into multiple parallel threads on the same node (if we have access to multiple CPU cores on that node at runtime). To make it run across multiple nodes, we need to cycle through a distributed domain or a distributed array, i.e. we should replace the loop:

  forall (i,j,k) in {1..nx,1..ny,1..nz} with (max reduce delta) { ... }

with

  forall (i,j,k) in largerMesh[1..nx,1..ny,1..nz] with (max reduce delta) { ... }

or

  forall (i,j,k) in largerMesh.expand(-1) with (max reduce delta) { ... }

First, let’s run the code at a small scale across four nodes:

# earlier serial run
# srun --unbuffered --time=1:0:0 --mem-per-cpu=3600 --account=... ./shared --nx=500 --niter=300 --nout=50
# At 500^3 after 300 iterations: delta=0.0810363 in 43.1899 sec, running at 868,259,455 stencils/s

submit with --mem-per-cpu=3600 --nodes=4 --tasks-per-node=3
At 500^3 after 300 iterations: delta=0.0810363 in 70.3028 sec, running at 533,406,646 stencils/s
CPU Efficiency: 79.86% of 00:16:48 core-walltime
Memory Efficiency: 5.36% of 42.19 GB (3.52 GB/core)

We can clearly see the parallel speedup but our code still runs slower than the serial code, now with 12 CPU cores.

To run the code at scale, let’s use all CPU cores on the four nodes, and increase the grid size to saturate their memory as well.

submit with --mem=0 --nodes=4 --tasks-per-node=192
./block -nl $SLURM_NNODES --nx=2000
At 2000^3 after 10 iterations: delta=2.29059 in 64.0843 sec, running at 1,248,355,428 stencils/s
At 3000^3 after 10 iterations: delta=2.29059 in 150.672 sec, running at 1,791,971,810 stencils/s
At 4000^3 after 10 iterations: delta=2.29059 in 277.831 sec, running at 2,303,559,517 stencils/s
CPU Efficiency: 36.33% of 10-01:55:12 core-walltime
Memory Efficiency: 23.97% of 2.93 TB (750.00 GB/node)
At 5000^3 after 10 iterations: delta=2.29059 in 365.152 sec, running at 3,423,232,512 stencils/s
CPU Efficiency: 34.03% of 8-23:28:00 core-walltime
Memory Efficiency: 46.77% of 2.93 TB (750.00 GB/node)
5200^3 => out of memory
Table 1: Serial code performance in Mstencils/s on Fir’s 4 full nodes
Resolution C+MPI BlockDist
2,000^3 69,629 1,248
3,000^3 71,413 1,792
4,000^3 70,275 2,304
5,000^3 68,302 3,423

At scale the block-decomposed parallel code runs so much slower …

Understanding StencilDist

Similar to BlockDist, StencilDist is a predefined multi-locale distribution in Chapel used to partition regular rectangular domains and arrays across available nodes.

Unlike BlockDist that was written for general-purpose contiguous partitioning of rectangular domains, StencilDist is optimized for neighbour communication for stencil patterns. In addition to local subdomains, it allocates extra boundary layers (“fluff” or “ghost cells”) around them and performs bulk updates via explicit updateFluff() calls, avoiding point-to-point network requests during stencil loops.

StencilDist in 2D.

Reading: The stencilDist distribution uses ghost cells as cached read-only values from other locales. When reading from a stencil-distributed array, the distribution will attempt to read from the local ghost cell cache first. If the index is not within the cached index set of the current locale, then we default to a remote read from the locale on which the element is located.

NoteIn a stencil, read T[i±1,j,k] and T[i,j±1,k] and T[i,j,k±1]

Near the block boundaries you need to read the fluff cell values.

Writing: Any write to array data will be applied to the actual element, the same as if you were using a Block-distributed array.

NoteIn a stencil, write Tnew[i,j,k]

You always write into the block-distribute array (no fluff cells).

This asymmetric read/write approach can cause problems if you are not careful. Consider the code below that we run on two locales:

source ~/startMultiLocale.sh
salloc --time=2:0:0 --mem-per-cpu=3600 --nodes=2 --cpus-per-task=1
make stencilMistake && ./stencilMistake -nl 2
use StencilDist, IO;
config const n = 8;
const mesh = {1..n, 1..n};
const D = stencilDist.createDomain(mesh, fluff=(1,1), periodic=false);
var A: [D] int;

// this writes into the mesh properly
A[1..n,1..n] = 1;

// reads local cells with fluff whenever possible, otherwise remote cells with fluff
writeln( A[0,0],        A[1,1],       A[5,5],        A[8,8],        A[9,9]         );
//       0=local_fluff  1=local_mesh  0=local_fluff  1=remote_mesh  0=remote_fluff

writeln('---\n', A);   // read the proper mesh
// 1 1 1 1 1 1 1 1
// 1 1 1 1 1 1 1 1
// 1 1 1 1 1 1 1 1
// 1 1 1 1 1 1 1 1
// 1 1 1 1 1 1 1 1
// 1 1 1 1 1 1 1 1
// 1 1 1 1 1 1 1 1
// 1 1 1 1 1 1 1 1

// these do not read the mesh correcty, as they mix mesh and fluff cells
// (happens when you start subsetting A in any way)
writeln('---\n', A[D]);   // mix of mesh and fluff
for loc in Locales do
  on loc {
    writeln("Locale ", here.id, "'s local array view:");
    writeln(A[A.localSubdomain()]);   // mix of mesh and fluff
  }

// you can read the entire mesh on every locale properly
if Locales.size > 1 {
  on Locales[1] do
    writeln(A);   // works, all 1's
}

if Locales.size > 1 {
  on Locales[1] {
    writeln(A[A.localSubdomain()]);   // subsetting => wrong, mix of mesh (1's) and fluff (0's)
    forall ij in A.localSubdomain() do
      writeln(ij, "  ", A[ij]);       // correct, all mesh elements on this locale (all 1's)
  }
}

// set the outer boundary (right-side and bottom-side): safer, should work even when mixing reads and writes
forall (i,j) in D.exterior(0,1) do A[i,j] = 80;   // right-side boundary, 1..n, n+1
forall (i,j) in D.exterior(1,0) do A[i,j] = 80;   // bottom-side boundary, n+1, 1..n

// set the outer boundary (right-side and bottom-side): should work for writes only
for i in 1..n do A[i,n+1] = 80;   // right-side boundary
for j in 1..n in A[n+1,j] = 80;   // bottom-side boundary

// wrong: this will print some local fluff instead of remote mesh
for (i,j) in D.expand(1) {
  write(A[i,j], " ");
  if j==n+1 then writeln("");
}

// correct: print the mesh and the outer boundary
var B: [0..n+1, 0..n+1] int; // local array for printing
B[1..n,1..n] = A;   // just the mesh
forall (i,j) in D.exterior(-1,0) do B[i,j] = A[i,j];
forall (i,j) in D.exterior(1,0) do B[i,j] = A[i,j];
forall (i,j) in D.exterior(0,-1) do B[i,j] = A[i,j];
forall (i,j) in D.exterior(0,1) do B[i,j] = A[i,j];
writeln(B);

StencilDist benchmarking

Here is our 3D heat diffusion solver with StencilDist:

use Time, StencilDist;

config const nx = 500, ny = nx, nz = nx, niter = 10, nout = 10, tolerance = 0.002;
var count = 0: int;

writef('Working with %ix%ix%i to %i iterations or dT below %r\n', nx, ny, nz, niter, tolerance);

const space = {1..nx, 1..ny, 1..nz};
const Dist = space dmapped new stencilDist(space, fluff=(1,1,1), periodic=false);
var T, Tnew: [Dist] real;
T[1..nx,1..ny,1..nz] = 25;     // initial temperature

for (i,j,k) in Dist.exterior(1,0,0) {   // rightmost x-boundary {nx+1,1..ny,1..nz}
  T[i,j,k] = 80.0;
  Tnew[i,j,k] = 80.0;
}
for (i,j,k) in Dist.exterior(0,1,0) {   // rightmost y-boundary {1..nx,ny+1,1..nz}
  T[i,j,k] = 80.0;
  Tnew[i,j,k] = 80.0;
}
for (i,j,k) in Dist.exterior(0,0,1) {   // rightmost z-boundary {1..nx,1..ny,nz+1}
  T[i,j,k] = 80.0;
  Tnew[i,j,k] = 80.0;
}

writef('Iteration 0: T=%r\n', T[1,1,1]);
var delta = tolerance*10;   // some safe initial large value
var watch: stopwatch;
watch.start();
while (count < niter && delta >= tolerance) {
  count += 1;
  delta = 0;
  T.updateFluff(); // update ghost cell buffers across nodes before the stencil computation
  forall (i,j,k) in Dist with (max reduce delta) {
    Tnew[i,j,k] = (T[i-1,j,k] + T[i+1,j,k] + T[i,j-1,k] + T[i,j+1,k] + T[i,j,k-1] + T[i,j,k+1]) / 6.0;
    var tmp = abs(Tnew[i,j,k]-T[i,j,k]);
    if tmp > delta then delta = tmp;
  }
  T <=> Tnew; // swap two arrays
  if count%nout == 0 then writef('Iteration %i: delta=%r T=%r\n', count, delta, T[1,1,1]);
}
watch.stop();
writef('At %ix%ix%i after %i iterations: delta=%r in %r sec, running at %i stencils/s\n',
       nx, ny, nz, count, delta, watch.elapsed(), ((nx:real*ny*nz*count)/watch.elapsed()): int);
chpl --fast stencil.chpl -o stencil
submit with --mem=0 --nodes=4 --tasks-per-node=192
./stencil -nl $SLURM_NNODES --nx=2000

correct numerical result!

At 2000^3 after 10 iterations: delta=2.29059 in 1.06842 sec, running at 74,876,921,061 stencils/s
At 3000^3 after 10 iterations: delta=2.29059 in 3.24749 sec, running at 83,141,184,817 stencils/s
At 4000^3 after 10 iterations: delta=2.29059 in 7.38194 sec, running at 86,698,064,912 stencils/s
CPU Efficiency: 3.20% of 5-16:32:00 core-walltime
Memory Efficiency: 24.63% of 2.93 TB (750.00 GB/node)

At 5000^3 after 10 iterations: delta=2.29059 in 14.1578 sec, running at 88,290,410,185 stencils/s
CPU Efficiency: 7.54% of 5-08:38:24 core-walltime
Memory Efficiency: 47.80% of 2.93 TB (750.00 GB/node)
5200^3 => out of memory
Table 2: Serial code performance in Mstencils/s on Fir’s 4 full nodes
Resolution C+MPI BlockDist StencilDist
2,000^3 69,629 1,248 74,877
3,000^3 71,413 1,792 83,141
4,000^3 70,275 2,304 86,698
5,000^3 68,302 3,423 88,290

Code length comparison

Here are the two codes side by side, with all comments removed:

C+MPI (left) and StencilDist (right)