|
SpECTRE
v2026.11.17
|
This tutorial builds a small parallel executable that estimates pi. Along the way, it introduces input-file options, DataBox tags, iterable and reduction actions, array and singleton parallel components, and the metavariables that connect those pieces. Read Parallelization in SpECTRE first if these terms are new to you.
The tutorial is based on Monte Carlo integration, which estimates an integral by averaging samples drawn at random. Consider the unit square and the quarter unit disk inside it. The square has area one and the quarter disk has area pi divided by four, so
\[ \frac{\pi}{4} = \int_0^1 \int_0^1 \mathbf{1}_{x^2 + y^2 < 1}\,\mathrm{d}x\,\mathrm{d}y. \]
Draw \(N\) points uniformly from the square and let \(H\) be the number for which \(x^2+y^2<1\). The fraction \(H/N\) approaches the area of the quarter disk as the sample grows, giving the estimator
\[ \widehat{\pi} = 4\frac{H}{N}. \]
The executable distributes this sampling work over the available processing elements (PEs). One DartThrower array element on each PE generates samples. The elements contribute their hit counts to a reduction, and a singleton PiEstimator receives the sum, updates the cumulative estimate, and either requests another iteration or lets the executable exit.
Before building the executable, let's look at the overall design. The executable holds an array parallel component whose elements throw darts and a singleton parallel component that collects results from each element of the array component, processes them, and decides whether to throw more darts or not, based on the accuracy of the estimate of pi so far. Each array component element and each parallel component get assigned to a cpu core when the code runs. Each core also has access to the GlobalCache.
Here is an illustration showing the communication pattern of the executable. Array component elements send how many of the darts they threw hit the unit quarter circle. The PiEstimator singleton handles the reduction, which combines data from each element (by addition in this case) to compute one overall estimate of pi. If the singleton determines the accuracy is not yet at the accuracy goal, it asks each element of the array component to throw some more darts (i.e., to sample some more random points).
In the commands below, SPECTRE_ROOT is the source directory and SPECTRE_BUILD_DIR is an already configured build directory. Work directly in src/Executables/Examples/PiMonteCarlo/PiMonteCarloStarter.cpp. Each TUTORIAL STEP comment marks where to edit. The completed example is in PiMonteCarlo.cpp in the same directory.
Build and run the starter.
The starter has an empty component list, so it needs no input file and exits without doing any work. This is intentional: it keeps every intermediate version runnable while you define types and actions that are not connected to the executable yet.
Use the two commands above as a checkpoint after every numbered step through step 3.4. Each intermediate version compiles and exits successfully. You may see unused-variable warnings while an action is only partly implemented; they disappear when the later lines use those variables. Starting with step 4.1, use the YAML-driven checkpoint shown in that step instead.
Input-file option tags describe values that the option parser should read. The example lets a user choose the number of samples generated per PE in one iteration and the fractional accuracy goal.
At TUTORIAL STEP 0.0, add these two option tags. The lower bounds prevent an empty sample, which would lead to division by zero, and a nonpositive accuracy goal, which would never terminate the iteration.
These types describe parsing but do not store values in a parallel component. That is the job of DataBox tags.
Each parallel component owns a DataBox. Simple tags name and describe the objects stored in it. See Motivation for SpECTRE's DataBox for a broader introduction.
At TUTORIAL STEP 1.0, add tags that initialize their values from the option tags in step 0.0:
The estimator also needs cumulative counters. At TUTORIAL STEP 1.1, add two tags initialized to zero without input-file options:
The DartThrower components will store only DartsPerIteration. The PiEstimator will store all four tags so it can accumulate results and decide when to stop.
The starter provides the action signatures. First complete the iterable action that runs independently on every DartThrower, then the reduction action that runs on the PiEstimator.
At TUTORIAL STEP 2.0, replace the temporary (void)box line with a DataBox lookup:
Generate points uniformly in the unit square and count the ones inside the quarter disk:
The engine is local to an action invocation, so different array elements do not share mutable random-number state.
An action communicates with parallel components through proxies stored in the global cache. Remove the temporary (void)cache and (void)array_index lines, then add:
The first proxy addresses the singleton. Indexing the array proxy gives a proxy for the DartThrower element running this action.
Package the local hit count as reduction data and contribute it. The reduction uses funcl::Plus to sum the values from all array elements before invoking ProcessHitsAndThrows on the singleton.
The action then returns Pause, as already written in the starter. Each array element remains paused until the estimator explicitly restarts it.
The reduction result contains hits from every PE, so the estimator needs the number of PEs to reconstruct the number of samples generated. Remove the temporary (void)cache line and add:
Read the per-iteration sample count from the estimator's DataBox:
Remove the temporary (void)new_hits line. Replace the empty db::mutate_apply call with this mutation, which updates both cumulative counters together:
The first typelist contains the tags to mutate. The second would contain read-only DataBox arguments passed to the lambda; it is empty because this lambda captures the other values directly.
Compute and print the estimate and its fractional difference from pi:
Parallel::printf serializes the output so messages from parallel work do not interleave like ordinary standard-stream output can.
If the estimate has not met the goal, get each DartThrower proxy and restart its algorithm:
When the goal has been met, the singleton sends no restart messages. All array elements remain paused, Charm++ detects quiescence, and SpECTRE advances to the exit phase.
Actions describe work, but parallel components specify where the actions run and what data they own.
Replace the empty PiEstimator definition at TUTORIAL STEP 3.0 with this singleton component:
The singleton has no iterable actions of its own. Its ProcessHitsAndThrows reduction action is invoked remotely when a reduction finishes.
At TUTORIAL STEP 3.1, define the phase-transition function declared above:
Replace the empty DartThrower definition at TUTORIAL STEP 3.2. This is an array component with integer indices and ThrowDarts as its iterable action in the execute phase.
Define the array component's phase transition at TUTORIAL STEP 3.3:
Finally, define how the array elements are allocated. This example creates one element per PE and assigns them round-robin while respecting any PEs that the resource options ask it to skip.
Nothing above has run yet because the temporary Metavariables::component_list is empty. The final part registers both components and changes the checkpoint from the empty smoke run to the real YAML-driven calculation.
Replace the empty component list at TUTORIAL STEP 4.1:
The executable now expects the options requested by those components. The example input file names PiMonteCarlo in its Executable metadata. Make a copy for PiMonteCarloStarter in the build directory.
Rebuild, check the input file, and run on two PEs.
The option check should report that the input file parsed successfully. The two-PE run prints estimates until it reaches the requested accuracy. Because the samples are random, the values and the number of iterations vary. Output includes a line similar to:
Replace the placeholder help string at TUTORIAL STEP 4.2:
Repeat the YAML-driven checkpoint from step 4.1. You can also inspect the completed executable's option help:
You have now assembled a complete task-parallel SpECTRE executable: array elements perform independent Monte Carlo work, a reduction combines their results, and a singleton controls iteration and termination.