Algorithmic Optimization Battle Report
Insights from optimizing projection (dimensionality reduction algorithms) with the goal of high speed and low RAM usage. Understand the problem conceptually first. And then trade compute vs space to match your requirements.
Understand what you need
Before getting lost in low-level software / hardware optimizations, spend time with pen and paper and get really clear about what it is you are tring to solve, because any time spent optimizing the wrong solution is wasted.
Design your algorithm with computational complexity (time and space) in mind, be aware that til certain input sizes a worse (higher complexity) algorhtm can in practice still be faster.
Example with PCA: If you only need two principal components, use a truncated or randomized PCA algorithm that targets the top two components. Avoid computing the full decomposition. Use random initialization where appropriate, and iterate until the desired convergence criterion is met.
Iterate on small representative datasets
do not waste time evaluating new optimizations on huge datasets waiting for results, instead validate them first on a small representative (random sample) dataset.
One important caveat: small datasets may fit entirely in CPU cache, hiding memory-bandwidth bottlenecks that appear on larger workloads (so not too small). Use small datasets for rapid iteration, but include a larger benchmark before drawing final performance conclusions.
Benchmark the actual bottleneck
profile which ops dominate program execution time and memory
Find the bottleneck:
- Compute-bound: limited by arithmetic throughput.
- Memory-bound: limited by memory bandwidth or latency.
- Overhead-bound: limited by allocation, synchronization or other operations.
Measure execution time, memory usage, cache misses, branch mispredictions, and vectorization efficiency. Every optimization needs to be validated and thus make sure your validation pipeline is fast and sound.
Approximations
Where can you get away with a cheap approximation / heuristic instead of paying for the full accurate baseline? Get clear about that and find cheap but useful approximations.
Cache Locality: RAM Is Not Random
Random Access Memory (RAM) benefits sequential memory access vs random access, so think about your memort data structure layout (pack things together than get accessed frequently together instead of rapidly fetching data from random locations). I was very confused by the random in RAM and assumed it would mean latency is uniform even for random access patterns but nope its not.
Data from RAM is being pre-emptively moved into CPU cache for faster access, thus write programs that produce predictable (sequential) heap access
For example, processing a matrix in cache-sized tiles can reduce repeated memory transfers compared with accessing scattered elements across the entire matrix.
Optimize memory access patterns:
Write code that makes the hardware cache behave much more favorably.
for (int i = 0; i < N; ++i) {
for (int j = 0; j < D; ++j) {
process(X[i * D + j]);
}
}
If X is stored in row-major order, this traverses its elements sequentially.
Compare that with:
for (int j = 0; j < D; ++j) {
for (int i = 0; i < N; ++i) {
process(X[i * D + j]);
}
}
The second version jumps between rows and can have significantly worse memory behavior.
Go Schnell aka parallel (SIMD)
use SIMD instructions for per core parallelized fast numerical operations where possible.
multi-threading allows to multiply that by core (thread) count.
Reduce unnecessary precision
float32 is rarely needed, go down to float16, int8 or even smaller where possible.
Reduce RAM Usage: Don't materialize what you can compute
For large projection algorithms, memory capacity can be just as important as computation time.
- Use streaming or chunked processing when the algorithm permits it.
- Reuse buffers instead of repeatedly allocating new arrays.
- Avoid materializing large intermediate matrices.
- Store only the information required for subsequent operations.
- Consider in-place operations when they are safe and practical.
For example, if you have a dataset (X) with shape (N \times D), computing the full covariance matrix (X^\top X) requires (D^2) storage, even if you ultimately want only two principal components.
Branchless
rule of thumbs: no comparisons (if statements etc) in hot loops.
Avoid unpredictable branches in hot loops, not all comparisons. Predictable branches can be cheaper than inefficient branchless alternatives.
Fuse Operations
minimize storage of data, pack as many numerical operations into one kernel / loop as possible.
Extra THOUGHTS: Why does no programming language let me manage CPU caching directly if it is so critical for max performance? or does ASM do it?
What you can do, including from C or C++ intrinsics:
Prefetch: __builtin_prefetch (PREFETCHT0/NTA) means "load this soon".
Non-temporal stores: _mm_stream_ps (MOVNT) writes without polluting the cache, which helps for big outputs you won't reread.
Flush or demote: CLFLUSHOPT and CLDEMOTE push lines out of a cache level.
Alignment: alignas(64) keeps data on cache-line boundaries and avoids false sharing.
Partitioning: Intel CAT and AMD's equivalent, via Linux resctrl, reserve last-level cache ways for a process. This is the closest thing to real control on a CPU.