A GPU case: flow past an obstacle
This page takes a complete GPU case, compiles it, runs it and explains what each
part is doing. It is tflbm/tclbm01.cu: two-dimensional channel
flow with a circular obstacle, driven by a parabolic inlet profile, with the inflow
and outflow boundary conditions written by hand as CUDA kernels.
That last part is the reason this case is worth reading. A lattice Boltzmann solver advances the fluid, but it does not know what you want at the edges of the box: an inlet with a prescribed velocity, an outlet that lets fluid leave quietly, a wall, a symmetry plane. MechSys gives you a hook that runs on every step, and you fill it in. This case is the worked example of that hook, and it is also a GPU case, so it shows how the data you need in those kernels gets onto the device.
The mechanics of compiling are on the first page. The CPU counterpart, which has no boundary conditions but does have contacts, is here.
The case
A channel 2400 cells long and 300 wide, with solid walls top and bottom and a circular obstacle near the inlet. Fluid enters at the left with a parabolic profile — fastest in the middle, zero at the walls, as in Poiseuille flow — and leaves at the right. Over the long stretch downstream the wake of the obstacle develops. The default Reynolds number is 40000.
The program
The file is tflbm/tclbm01.cu in the tree, with the usual
GPL banner on top, which is left out here. As with the CPU case, you can copy it out
and call it whatever you want; only the .cu extension means anything.
// FLow in a pipe with obstacle
// MechSys
#include <mechsys/flbm/Domain.h>
struct UserData
{
thrust::device_vector<real> Vel;
real * pVel;
real vmax;
real rho;
};
__global__ void Left_BC(real * VBC, bool * IsSolid, real * F, real3 * Vel, real * Rho, FLBM::lbm_aux * lbmaux)
{
size_t ic = threadIdx.x + blockIdx.x * blockDim.x;
if (ic>=lbmaux[0].Ny) return;
size_t ib = ic*lbmaux[0].Nx;
if (!IsSolid[ib])
{
//" Initialize(ib,F,Rho,Vel,1.0,(real3)(VBC[ic],0.0,0.0),lbmaux); \n"
// F is direction-major now (FLBM::FIDX in flbm/lbm.cuh), so the
// populations of a cell are not contiguous: gather them first and
// scatter them back once the boundary values have been computed.
real f[27];
for (size_t k=0;k<lbmaux[0].Nneigh;k++) f[k] = F[FLBM::FIDX(lbmaux[0].Ncells,lbmaux[0].Nneigh,0,k,ib)];
real rho = (f[0]+f[2]+f[4] + 2.0*(f[3]+f[6]+f[7]))/(1.0-VBC[ic]);
f[1] = f[3] + (2.0/3.0)*rho*VBC[ic];
f[5] = f[7] + (1.0/6.0)*rho*VBC[ic] - 0.5*(f[2]-f[4]);
f[8] = f[6] + (1.0/6.0)*rho*VBC[ic] + 0.5*(f[2]-f[4]);
for (size_t k=0;k<lbmaux[0].Nneigh;k++) F[FLBM::FIDX(lbmaux[0].Ncells,lbmaux[0].Nneigh,0,k,ib)] = f[k];
Rho [ib] = 0.0;
Vel [ib] = make_real3(0.0,0.0,0.0);
for(size_t k=0;k<lbmaux[0].Nneigh;k++)
{
Rho[ib] += f[k];
Vel[ib] = Vel[ib] + f[k]*lbmaux[0].C[k];
}
Vel[ib] = (1.0/Rho[ib])*Vel[ib];
}
}
__global__ void Right_BC(bool * IsSolid, real * F, real3 * Vel, real * Rho, FLBM::lbm_aux * lbmaux)
{
size_t ic = threadIdx.x + blockIdx.x * blockDim.x;
if (ic>=lbmaux[0].Ny) return;
size_t ib = ic*lbmaux[0].Nx + lbmaux[0].Nx-1;
if (!IsSolid[ib])
{
//" Initialize(ib,F,Rho,Vel,1.0,Vel[ib],lbmaux); \n"
real f[27];
for (size_t k=0;k<lbmaux[0].Nneigh;k++) f[k] = F[FLBM::FIDX(lbmaux[0].Ncells,lbmaux[0].Nneigh,0,k,ib)];
real rho = 1.0;
real vx = -1.0 + (f[0]+f[2]+f[4] + 2.0f*(f[1]+f[5]+f[8]))/rho;
f[3] = f[1] - (2.0/3.0)*rho*vx;
f[7] = f[5] - (1.0/6.0)*rho*vx + 0.5*(f[2]-f[4]);
f[6] = f[8] - (1.0/6.0)*rho*vx - 0.5*(f[2]-f[4]);
for (size_t k=0;k<lbmaux[0].Nneigh;k++) F[FLBM::FIDX(lbmaux[0].Ncells,lbmaux[0].Nneigh,0,k,ib)] = f[k];
Rho [ib] = 0.0;
Vel [ib] = make_real3(0.0,0.0,0.0);
for(size_t k=0;k<lbmaux[0].Nneigh;k++)
{
Rho[ib] += f[k];
Vel[ib] = Vel[ib] + f[k]*lbmaux[0].C[k];
}
Vel[ib] = (1.0/Rho[ib])*Vel[ib];
}
}
void Setup (FLBM::Domain & dom, void * UD)
{
UserData & dat = (*static_cast<UserData *>(UD));
Left_BC<<<dom.Ndim(1)/256+1,256>>>(dat.pVel,dom.pIsSolid,dom.pF,dom.pVel,dom.pRho,dom.plbmaux);
//cudaDeviceSynchronize();
Right_BC<<<dom.Ndim(1)/256+1,256>>>(dom.pIsSolid,dom.pF,dom.pVel,dom.pRho,dom.plbmaux);
//cudaDeviceSynchronize();
}
int main(int argc, char **argv) try
{
size_t Nproc = 1;
double u_max = 0.1; // Poiseuille's maximum velocity
double Re = 40000.0; // Reynold's number
if (argc==2) Re=atof(argv[1]);
size_t nx = 2400;
size_t ny = 300;
int radius = ny/10 + 1; // radius of inner circle (obstacle)
double nu = u_max*(2*radius)/Re; // viscocity
FLBM::Domain Dom(D2Q9, nu, iVec3_t(nx,ny,1), 1.0, 1.0);
UserData dat;
Dom.UserData = &dat;
dat.vmax = u_max;
dat.Vel.resize(ny);
for (size_t i=0;i<ny;i++)
{
// set parabolic profile
double L = ny - 2; // channel width in cell units
double yp = i - 1.5; // ordinate of cell
double vx = dat.vmax*4/(L*L)*(L*yp - yp*yp); // horizontal velocity
dat.Vel[i] = vx;
}
dat.pVel = thrust::raw_pointer_cast(dat.Vel.data());
dat.rho = 1.0;
// set inner obstacle
int obsX = ny/2; // x position
int obsY = ny/2+3; // y position
for (size_t i=0;i<nx;i++)
for (size_t j=0;j<ny;j++)
{
if ((i-obsX)*(i-obsX)+(j-obsY)*(j-obsY)<radius*radius)
{
Dom.IsSolid[0][i][j][0] = true;
}
}
//Assigning solid boundaries at top and bottom
for (size_t i=0;i<nx;i++)
{
Dom.IsSolid[0][i][0][0] = true;
Dom.IsSolid[0][i][ny-1][0] = true;
}
double rho0 = 1.0;
Vec3_t v0(0.08,0.0,0.0);
for (size_t ix=0;ix<nx;ix++)
for (size_t iy=0;iy<ny;iy++)
{
iVec3_t idx(ix,iy,0);
Dom.Initialize(0,idx,rho0,v0);
}
Dom.Solve(40000.0,400.0,Setup,NULL,"tclbm01",true,Nproc);
}
MECHSYS_CATCH
Step by step
The lattice and the domain
FLBM::Domain Dom(D2Q9, nu, iVec3_t(nx,ny,1), 1.0, 1.0);
The lattice is D2Q9 — two dimensions, nine velocities — and the third dimension is 1, which is how a two-dimensional problem is expressed. The last two arguments are the grid spacing and the time step, both 1, so the simulation is in lattice units: lengths are counted in cells and the speed of sound is 1/√3. The viscosity is the only physical parameter that survives into the lattice, which is why it is computed so carefully in the next step.
Reynolds number and viscosity
double nu = u_max*(2*radius)/Re;
The Reynolds number is built on the obstacle diameter, so Re = u·d/ν rearranges into this. With the defaults — u_max = 0.1, radius = 31, Re = 40000 — the diameter is 62 cells and ν = 1.55e-4. The relaxation time follows from the viscosity, and the run reports it:
Tau = 3 nu dt/dx^2 + 0.5 = 3 * 1.55e-4 + 0.5 = 0.500465
That number is worth watching in any LBM run. The scheme is only stable for τ > 0.5, and as τ approaches 0.5 from above the simulation becomes fragile. Here it is 0.500465, which is close to the limit: that is what a high Reynolds number costs, and it is the reason a case like this wants a small u_max. If a run goes unstable, the first thing to check is τ.
The case takes Re from the command line, so the same binary can be run at different Reynolds numbers without recompiling:
user@mach: ~/myproject $ ./pipe 1000
The solid cells
Dom.IsSolid[0][i][j][0] = true;
Boundaries in LBM are not mesh entities; they are cells that are flagged as not being fluid. The obstacle is a disc in the (i,j) plane, and the walls are the first and last rows. Indexing is [component][x][y][z], the leading 0 being the single fluid component, and the trailing 0 the single layer in z.
The obstacle is placed at obsX = ny/2 = 150 and obsY = ny/2+3 = 153. Note that the x position comes from ny, not from nx: the obstacle sits 150 cells in, near the inlet of a 2400-cell channel, leaving 2250 cells for the wake to develop in. The +3 lifts it very slightly off the centre line, which breaks the symmetry of the problem so that the wake is free to become asymmetric, as it must at high Reynolds number.
The initial condition
double rho0 = 1.0;
Vec3_t v0(0.08,0.0,0.0);
for (size_t ix=0;ix<nx;ix++)
for (size_t iy=0;iy<ny;iy++)
{
iVec3_t idx(ix,iy,0);
Dom.Initialize(0,idx,rho0,v0);
}
Every cell starts at unit density with a uniform velocity of 0.08 in x. This is not the final solution — it is nowhere near the parabolic profile — it is just a starting state. A uniform flow is a reasonable choice because it is divergence-free and close to what the inlet will impose, so the transient at the start is short.
The inlet profile on the device
thrust::device_vector<real> Vel;
...
dat.pVel = thrust::raw_pointer_cast(dat.Vel.data());
This is the part that makes it a GPU case. The parabolic inlet profile is one number per row — 300 of them — and the kernel needs them on the card. A thrust::device_vector is the easy way to get that: it allocates in device memory and manages the lifetime, and raw_pointer_cast hands you the bare pointer the kernel needs. Asking for the plain std::vector's pointer instead is a classic mistake that either fails to compile or, worse, passes a host address to a kernel.
The profile itself is a parabola:
double L = ny - 2;
double yp = i - 1.5;
double vx = dat.vmax*4/(L*L)*(L*yp - yp*yp);
L is the width between the walls, since the two wall rows are not fluid. yp measures the row from the first fluid row, with a half-cell offset of 1.5 that reflects where the wall actually is relative to the cell centre. The result is a parabola that is zero at yp = 0 and yp = L, with its maximum vmax in the middle. Vanishing at both walls is what makes it consistent with the no-slip walls.
Why the boundary conditions need your own code
The solver knows how to stream and collide; it does not know what you want at the edges. What it gives you is Dom.UserData, a void* attached to the domain, and a setup callback passed to Solve that is called once per step:
void Setup (FLBM::Domain & dom, void * UD)
{
UserData & dat = (*static_cast<UserData *>(UD));
Left_BC<<<dom.Ndim(1)/256+1,256>>>(dat.pVel,dom.pIsSolid,dom.pF,dom.pVel,dom.pRho,dom.plbmaux);
Right_BC<<<dom.Ndim(1)/256+1,256>>>(dom.pIsSolid,dom.pF,dom.pVel,dom.pRho,dom.plbmaux);
}
UD is the pointer you stored in Dom.UserData, cast back to your own struct, which is how the kernels get at the inlet profile.
The launch configuration is one thread per row: ny = 300 rows, in blocks of 256, so 300/256+1 = 2 blocks of which the second is mostly idle. The kernels begin with if (ic >= lbmaux[0].Ny) return;, which is what makes the overshoot harmless. Each thread then works on the single cell at one end of its row.
The device pointers used here — dom.pIsSolid, dom.pF, dom.pVel, dom.pRho, dom.plbmaux — are the domain's own arrays on the card. pF is the population array, pRho and pVel the macroscopic fields, pIsSolid the flags, and plbmaux a small structure holding the sizes, the direction vectors C and the weights. The domain has already copied everything to the device by this point, so the callback works entirely on the card and nothing is transferred per step.
Which direction is which
The formulas look cryptic until you know the numbering. For D2Q9 the nine directions are:
f[0] ( 0, 0) at rest f[5] ( 1, 1) diagonally up-right
f[1] ( 1, 0) +x f[6] (-1, 1) diagonally up-left
f[2] ( 0, 1) +y f[7] (-1,-1) diagonally down-left
f[3] (-1, 0) -x f[8] ( 1,-1) diagonally down-right
f[4] ( 0,-1) -y
A population f[k] is the density of particles at a cell about to move in direction k. At a boundary some of those directions point into the domain and some point out of it. The ones pointing into the domain came from a neighbour and are known after streaming; the ones pointing out are unknown, and the boundary condition is a rule for computing them from the known ones plus whatever you are imposing.
The inlet kernel
At the left wall the flow enters in the +x direction, so the unknown populations are the three with a positive x component: f[1], f[5] and f[8]. The imposed velocity is VBC[ic], the profile value for that row. The rule used is the standard Zou-He treatment:
real rho = (f[0]+f[2]+f[4] + 2.0*(f[3]+f[6]+f[7]))/(1.0-VBC[ic]);
f[1] = f[3] + (2.0/3.0)*rho*VBC[ic];
f[5] = f[7] + (1.0/6.0)*rho*VBC[ic] - 0.5*(f[2]-f[4]);
f[8] = f[6] + (1.0/6.0)*rho*VBC[ic] + 0.5*(f[2]-f[4]);
Read it in two parts. The first line computes the density at the boundary from the populations that are known, with the 2(f[3]+f[6]+f[7]) reflecting the bounce back off the wall of the ones heading out, and the (1-VBC) accounting for the momentum the imposed velocity carries. The remaining three lines then set each unknown to its opposite number, which is the part coming from inside the domain, plus a correction proportional to the imposed velocity. The ±0.5(f[2]-f[4]) terms couple the two diagonal pairs and are what makes the scheme second order rather than a crude extrapolation.
The coefficients 2/3 and 1/6 are the D2Q9 weights for the axial and diagonal directions. The result is a boundary where the velocity is exactly what you asked for and the density is whatever is needed for consistency.
After setting the populations the kernel recomputes Rho and Vel for that cell from the new values, so that the macroscopic fields agree with the populations that were just written. The commented Initialize(...) line above the formulas is what the kernel used to call before the population array was reorganised; it is left there as a reminder of what is being done by hand.
The outlet kernel
At the right wall the flow leaves in the +x direction, and the unknown populations are the three pointing the other way: f[3], f[7] and f[6]. Rather than impose a velocity here, the kernel takes the density as 1 and infers the velocity from the populations arriving at the boundary:
real rho = 1.0;
real vx = -1.0 + (f[0]+f[2]+f[4] + 2.0f*(f[1]+f[5]+f[8]))/rho;
f[3] = f[1] - (2.0/3.0)*rho*vx;
f[7] = f[5] - (1.0/6.0)*rho*vx + 0.5*(f[2]-f[4]);
f[6] = f[8] - (1.0/6.0)*rho*vx - 0.5*(f[2]-f[4]);
This is the mirror image of the inlet, and it is what lets fluid leave without reflecting back into the domain and spoiling the solution upstream. Fixing the density and letting the velocity float is a common choice for an outlet: the flow is free to come out at whatever rate the interior dictates.
Why the populations are gathered and scattered
Both kernels do this:
real f[27];
for (size_t k=0;k<lbmaux[0].Nneigh;k++) f[k] = F[FLBM::FIDX(...,k,ib)];
...
for (size_t k=0;k<lbmaux[0].Nneigh;k++) F[FLBM::FIDX(...,k,ib)] = f[k];
rather than reading and writing F[ib*9+k] as a CPU case would. In a GPU build the population array is stored direction-major: the index is
FIDX(Ncells, Nneigh, component, k, cell) = (component*Nneigh + k)*Ncells + cell
so for a fixed direction k the cells are contiguous, and the nine populations of one cell are far apart. On a GPU that is the right layout: a warp of 32 threads advancing one direction across 32 neighbouring cells reads 32 consecutive values and touches a single memory sector, where the cell-major layout would touch 32 different sectors to use 8 bytes out of each. The kernels that do the streaming rely on exactly this. The price is that a boundary kernel, which needs all nine populations of one cell, has to gather them into a local array first and scatter them back afterwards. That is all the real f[27] is for — 27 rather than 9 so the same code works for the three-dimensional lattices.
Solving
Dom.Solve(40000.0,400.0,Setup,NULL,"tclbm01",true,Nproc);
The arguments are the final time, the output step, the setup callback, a report callback, the file key, whether to run on the GPU, and the number of processes. The NULL here is the report callback, which this case does not use; the Setup callback is the one carrying the boundary conditions, and it runs before each step.
The "tclbm01" is the file key, and it names every file the run writes. Like the CPU case, it is a string inside the code rather than anything the build command sets, so it is the one thing to edit if you rename the file.
A final time of 40000 steps with output every 400 is 100 output files. Given the size of the domain, that is worth thinking about before hitting enter.
Compiling and running
Save the code wherever you like, under whatever name you like. Only the .cu extension matters, because that is what sends it through nvcc:
user@mach: ~ $ mkdir myproject
user@mach: ~ $ cd myproject
user@mach: ~/myproject $ cp ~/mechsys/tflbm/tclbm01.cu pipe.cu # or paste it in by hand
user@mach: ~/myproject $ ~/mechsys/mechsyscc pipe.cu -o pipe
user@mach: ~/myproject $ ./pipe
Nothing has to be inside the MechSys tree, and the script does not have to be run from there either — ~/mechsys/mechsyscc is an ordinary path to it. The executable is written into the directory you run the command from.
This copy is called pipe, so it is worth changing the file key in Solve from "tclbm01" to "pipe" before running it, or the output will be tclbm01_0000.h5 and its 99 siblings rather than anything matching the name you chose. The rest of this page says tclbm01 for the output because that is what an unchanged copy produces.
The .cu extension is what sends it through nvcc. On an RTX A6000 the run takes about 53 seconds:
--- Initializing LBM Domain --------------------------------------------
Num of cells = 720000
Num of cells x = 2400
Num of cells y = 300
Num of cells z = 1
--- Solving ---------------------------------------------------------------------
Number of cores = 1
Time step = 1
Grid size = 1
C parameter = 1
Number of LBM cells = 720000
Tau of Lattice 0 = 0.500465
Simulated Time = 40000
Using GPU: = NVIDIA RTX A6000
Elapsed time = 52.736234s CPU 53.265966s (16:27:02 => 16:27:55)
If Using GPU: names your card, the whole path worked: the kernels compiled for the right architecture, the data made it to the device, and both boundary kernels ran. That line is the one to check when a GPU case runs suspiciously slowly, because a case that silently fell back to the CPU looks identical apart from that line.
What to look at
The run writes tclbm01_0000 to tclbm01_0099, each an .h5 with a matching .xmf. Open the .xmf in ParaView, colour by velocity magnitude, and you should see the parabolic profile at the inlet, the acceleration of the fluid over the top of the obstacle, the recirculation immediately behind it, and a wake that grows and becomes unsteady downstream. Nothing in the case prints the physics, so the fields are the result.
Two checks worth making on a run of your own. The inlet profile should reach u_max = 0.1 at the centre and fall to zero at both walls; if it does not, the half-cell offset in the profile formula is inconsistent with where the walls are. And the velocity should never approach the speed of sound, 1/√3 ≈ 0.577 in lattice units, because the whole scheme is a low-Mach approximation. At 0.1 the case is comfortably inside it.
Things that bite
τ too close to 0.5. At Re = 40000 it is 0.500465, which is nearly as close as this scheme tolerates. Raising Re lowers ν and pushes τ towards 0.5 until the run blows up. The cure is a larger u_max, a bigger domain, or a lower Reynolds number — not a smaller time step.
Passing a host pointer to a kernel. Taking the address of an ordinary std::vector gives a host address. Use thrust::device_vector and raw_pointer_cast, as the case does.
Forgetting the bounds check. dom.Ndim(1)/256+1 blocks of 256 threads always overshoots the number of rows. Without the if (ic >= ...) return; the extra threads read and write past the edge of the arrays.
Reading the macros before the boundary kernels run. The kernels update pRho and pVel as well as the populations. If you add a report callback that inspects the fluid, remember it runs at the point in the step where MechSys calls it, and the boundary cells are only correct after these kernels have run.
Assuming a build without CUDA fails at compile time. MechSys can be
configured without CUDA, and this case will not build then. Check
./mechsys-config --nvcc if mechsyscc seems to be ignoring the
.cu extension.
A cluster, and GLIBCXX
Compiling on a head node and running on a node with a card is the usual arrangement, and it needs the architecture to be chosen explicitly, since the head node has no GPU to detect. That is covered on the first page.
The failure that actually costs people days on a cluster looks like this:
./pipe: /usr/lib64/libstdc++.so.6: version `GLIBCXX_3.4.32' not found
It has nothing to do with MechSys or with CUDA. Clusters commonly have a very old system libstdc++ — on CentOS 8 that is the GCC 8 one, whose newest symbol is GLIBCXX_3.4.25 — while the compiler you build with is a newer module, say GCC 14. The program is built correctly, but at startup the loader finds the old libstdc++.so.6 first and the symbols are simply not in it.
The version numbers date the compiler that built the binary: 3.4.26 is GCC 9, 3.4.29 is GCC 11, 3.4.32 is GCC 12 or later. If they are all newer than the machine's, the build and run environments disagree.
The first and best fix is to load the same module when running as when compiling, and to make sure the job script does not quietly lose it:
module load gcc/14.1.0
export LD_LIBRARY_PATH=/soft/compiler/gcc/gcc-14.1.0/lib64:$LD_LIBRARY_PATH
./pipe
If neither is possible, MechSys can remove the dependency rather than chase it:
user@mach: ~/mechsys $ cmake -DA_USE_STATIC_LIBSTDCXX=ON .
which links libstdc++ and libgcc into the binary for about a megabyte per program. It is off by default, because loading the right module is cleaner, and because a static libstdc++ mixed with shared libraries built against a different one is worth avoiding unless the mismatch actually bites.
Two commands make the diagnosis quick. The first says what the binary asks for, the second what the loader will find and from where:
user@mach: ~/myproject $ readelf -d pipe | grep -E 'NEEDED|RPATH|RUNPATH'
user@mach: ~/myproject $ ldd pipe | grep libstdc
Use readelf rather than ldd for the first of those. ldd reports indirect dependencies too, so it lists libstdc++ even when your binary does not ask for it directly, which is misleading exactly when you are trying to work out who does.