Performance development guidelines¶
These notes are for a change that touches the GP hot path: covariance assembly, factorisation, the gradient of the hyperparameter objective and the optimizer loop. A change there is worth making only when a measurement says the path matters for the search, and worth keeping only when a second measurement shows it helped. The rules below are habits that keep the path cheap and its arithmetic stable.
Status: guidance for contributors. Each rule that names a source file is applied there as of this revision. Rules without a file are conventions.
Measure first¶
Find out which phase dominates before changing code.
Where the time goes gives one
measured split and the call path of a hyperparameter evaluation.
Find where a search spends its time lists
the timers and profiler tasks. State the source of every timing in a pull
request or a document: the benchmark script, the CSV under bench/ or the
test that produced it. A timing without a named source cannot be checked and
does not belong in the documentation.
Rules for the hot path¶
Prefer Eigen block operations to scalar loops¶
Eigen’s block, segment and diagonal accessors map to vectorised kernels or bulk copies. A scalar loop over raw pointers does not.
// Avoid
for (Eigen::Index i = 0; i < C.rows(); ++i) C(i, i) = sigma2;
// Prefer
C.diagonal().setConstant(sigma2);
ConstantCF::calculateCovarianceMatrix fills its matrix with
C.setConstant(...), and the derivative blocks start from setZero()
(gpr/covariance_functions/ConstantCF.cpp).
GaussianProcessRegression::extractCoordinatesByIndex copies one contiguous
block per call instead of testing each row
(gpr/ml/gp/CovarianceAssembly.cpp).
Compute loop-invariant values once¶
A value that depends only on the outer loop variable belongs outside the inner loop.
// Avoid: recomputes the x2 norm for every (n, m) pair
for (n ...) {
for (m ...) {
double invr2 = 1.0 / (coord::at(x2, m, j) - coord::at(x2, m, i)).norm();
...
}
}
// Prefer: compute the x2 quantities before the n loop
std::vector<double> invr2(n2);
for (m ...) invr2[m] = 1.0 / (coord::at(x2, m, j) - coord::at(x2, m, i)).norm();
for (n ...) {
for (m ...) {
double diff = invr1 - invr2[m];
...
}
}
The same applies to positions that do not change across iterations. Extract a
frozen atom’s position with gpr::coord::at once at the loop level where it
is invariant, not in the innermost loop.
Do not allocate inside iteration loops¶
Eigen::VectorXd allocates when it is constructed. Allocate before the loop
and reuse the storage with .noalias(). The ADAM loop allocates m_hat,
v_hat and w_update once before iterating and updates the moments in place
(gpr/ml/ADAM.inl).
Eigen::VectorXd m_hat(nparams), v_hat(nparams); // before the loop
m_hat.noalias() = m / (1.0 - beta1_t); // in the loop, reuses storage
Use .noalias() for products with a distinct destination¶
When the destination does not alias an operand, .noalias() removes the
temporary that Eigen would otherwise create:
C.noalias() = A * B;
Reuse what does not depend on the hyperparameters¶
The block geometry of the training kernel does not change while the
hyperparameters vary. The objective builds a TrainingKernelGeometry once per
fit and passes it to every evaluation
(GaussianProcessRegression::evaluateEnergyAndGradient,
gpr/ml/gp/EnergyGradient.cpp). New code in the objective should take its
geometry from that object and not recompute it per evaluation.
Keep the arithmetic order of the reproducible kernels¶
The distributed factorisation, solves and products fix their tile dimensions
and accumulation order so that results agree bit for bit across rank and
thread counts (see
Where the time goes).
tests/gpr/linalg/TileProductTest.cpp compares every bit. A speed-up that
reorders a sum in those kernels changes the result. Add or extend a bitwise
test with the change, and see
Check run-to-run determinism for the
repeatability check on a full run.
Memory layout¶
GPRidge mixes Eigen storage orders. The aliases are defined in
backend/Macros.h.
Type |
Storage |
Used for |
|---|---|---|
|
RowMajor |
Observations, coordinates |
|
ColMajor |
Covariance matrices, linear algebra |
assembleVectorFromEnergyAndGradient copies the gradient in column-major
order so that it matches the ind_Ddim block structure: all \(\partial E/\partial x\)
entries first, then \(\partial E/\partial y\), then \(\partial E/\partial z\)
(gpr/auxiliary/AdditionalFunctionality.h). The covariance matrix layout
requires this order. It is not a performance choice.
Benchmark a change¶
pixi run -e python bench compares the current checkout with the base branch
(default main) in separate worktrees and virtual environments. The commands
and their options are in
Find where a search spends its time,
section “Compare two versions of the code”. The script is
scripts/bench_compare.nim. It builds both branches in parallel and runs the
benchmarks one after another so that they do not compete for CPU time.
Add a benchmark¶
Benchmarks use airspeed-velocity conventions and live in
benchmarks/bench_gpr.py. A benchmark class names its parameters, builds its
input in setup, which is not timed, and times the methods whose names start
with time_.
class TimeMyOperation:
params = [10, 20, 40]
param_names = ["n_obs"]
def setup(self, n_obs):
...
def time_my_operation(self, n_obs):
...
Before you open the pull request¶
Run
pixi run -e python benchbefore and after the change, and keep the output.Confine the change to the phase that the measurement shows to dominate.
Check that results are unchanged where the change does not intend to alter them: run the tests, and for the reproducible kernels run the bitwise tests.
Add a towncrier fragment of type
changedunderdocs/newsfragments/. The contributing guide gives the file naming rule.