From 76ca6478609163ae326f7ecf7725bba7ca448804 Mon Sep 17 00:00:00 2001 From: Murilo Marinho Date: Thu, 1 Oct 2026 17:58:14 +0100 Subject: [PATCH 1/2] Benchmark compiler optimization flags; add opt-in OSQP_OPT_FAST_MATH Benchmarks g++/gcc/clang optimization levels for the solver core (OSQP ADMM loop + built-in algebra + qdldl/AMD factorizer) and documents the findings in BENCHMARK.md, with a reproducible harness under bench/. Findings (Apple M2 arm64): - -O3 is already the sweet spot; -O2/-O1 are within noise, -O0 ~3x slower. - -march=native and -flto give no measurable gain on this workload. - -ffast-math speeds up the C OSQP core ~25-30% (and ~4% end-to-end through the Python wrapper, whose dense->CSC conversion dominates). Change: add an opt-in OSQP_OPT_FAST_MATH CMake option (OFF by default, so the shipped wheel stays IEEE-conformant -O3). It appends -ffast-math (/fp:fast on MSVC) to the base C/CXX flags before add_subdirectory(osqp), so it reaches the vendored OSQP/qdldl as well as the wrapper. All 46 tests pass on both the default and the fast-math build, with identical solutions. Co-authored-by: openhands --- .gitignore | 6 + BENCHMARK.md | 211 ++++++++++++++++++++++++++++++++ CMakeLists.txt | 22 ++++ bench/aggregate.py | 36 ++++++ bench/build.sh | 171 ++++++++++++++++++++++++++ bench/osqp_bench.c | 289 ++++++++++++++++++++++++++++++++++++++++++++ bench/run.sh | 24 ++++ bench/scan_flags.py | 44 +++++++ 8 files changed, 803 insertions(+) create mode 100644 BENCHMARK.md create mode 100644 bench/aggregate.py create mode 100755 bench/build.sh create mode 100644 bench/osqp_bench.c create mode 100755 bench/run.sh create mode 100644 bench/scan_flags.py diff --git a/.gitignore b/.gitignore index 21e8fea..dbf0113 100644 --- a/.gitignore +++ b/.gitignore @@ -6,9 +6,15 @@ dist/ .deb-out/ obj-*/ +# Benchmark output (bench/*.sh, bench/*.py are the harness; these are its output) +bench/bin/ +bench/gen/ +bench/results/ + # Python caches __pycache__/ *.py[cod] +.pytest_cache/ # npm (e.g. locally installed pyright) node_modules/ diff --git a/BENCHMARK.md b/BENCHMARK.md new file mode 100644 index 0000000..508041e --- /dev/null +++ b/BENCHMARK.md @@ -0,0 +1,211 @@ +# Compiler Optimization Benchmark + +This documents a benchmark of `g++`/`gcc`/`clang` optimization flags for the +`marinholab-solvers-osqp` package, what each flag actually does to the code that +dominates solve time, and the resulting change (an opt-in `OSQP_OPT_FAST_MATH` +CMake option). + +## TL;DR + +* The heavy lifting in a solve is **OSQP itself** (the ADMM iteration loop, its + built-in CSC algebra, and the qdldl/AMD LDL^t factorizer). The Python/C++ + wrapper (`src/core_function.cpp`) is thin glue: it converts dense `Eigen` + matrices to CSC and calls `osqp_setup`/`osqp_solve`. +* The vendored `osqp/` and `qdldl/` submodules **force `-O3`** on their C code + in their own `CMakeLists.txt`, regardless of the top-level build type. The + wrapper C++ compiles under the top-level build type (`Release` → `-O3`). + So the shipped wheel is already built at `-O3` everywhere. +* Going from `-O3` to `-O2`/`-O1` is **not** a speedup, and `-march=native` + and `-flto` give **no measurable gain** on this workload. +* The one flag that moves the needle is **`-ffast-math`** (a.k.a. the + fast-math part of `-Ofast`): it makes the C OSQP core ~**25–30% faster** in + the steady-state ADMM loop. Because the dense-matrix→CSC conversion in the + wrapper is a large, fast-math-insensitive cost, the end-to-end Python solve + time improves by a more modest ~**4–8%**. +* `-ffast-math` relaxes IEEE-754. It does **not** change the solutions this + package produces in the tests or example (answers are identical to the `-O3` + build, with only machine-precision-level differences in residuals), because + OSQP is an iterative solver that runs to a tolerance. + +**Decision:** keep the default build at the IEEE-conformant `-O3` (matching +OSQP's own default), and expose the fast-math option as an **opt-in** CMake +flag, `OSQP_OPT_FAST_MATH` (OFF by default), so a consumer who can tolerate the +relaxed floating-point contract can opt into the speedup without changing the +shipped wheel. + +## Environment + +| Item | Value | +| --- | --- | +| Host | Apple M2, arm64 (macOS) | +| Compiler | Apple clang 21 (`cc`; `gcc`/`g++` are clang on macOS) | +| OSQP | submodule `1572ae06` (≈ v1.0.0) | +| qdldl | submodule `138fdac58` (v0.1.8) | +| pybind11 | submodule `d03662f0` (v3.0) | +| Python | 3.12 | + +The numbers below are from this host; relative ratios are what matter, and the +harness is included so results can be re-produced on any machine. + +## Methodology + +The benchmark compiles **exactly the C sources the package links** (OSQP solver ++ built-in algebra + the AMD/qdldl factorizer) with a chosen set of compiler +flags, then times two deterministic workloads. Compiling the C core directly +(rather than rebuilding the whole CMake tree per variant) guarantees that *only +the optimization flags* differ between runs. + +* **Workloads** — a "small" dense-SPD QP (n=800) and a "large" one (n=2500), + each with box constraints plus a few equality rows. The Hessian is + `P = M'M + n·I` (dense, symmetric positive definite), mirroring how the Python + wrapper feeds OSQP: it converts a *dense* `Eigen::MatrixXd` Hessian to CSC, so + in practice the top-left KKT block is dense. +* **Cold-start solves** — `warm_starting = 0`, `polishing = 0`, + `eps_abs = eps_rel = 1e-6`, so every `osqp_solve` runs a stable ~50 + iterations and the ADMM loop does real work (warm-starting on identical data + converges in ~25 iterations, which is too cheap to time). +* **Timed** — `osqp_setup` (factorization-heavy) and steady-state + `osqp_solve`, averaged over many reps. Data is fixed (seed 42), so all + variants solve the identical problem; the objective value is printed so a + run can be checked for correctness. + +### Flags benchmarked + +| Variant | Flags | Rationale | +| --- | --- | --- | +| `o0` | `-O0 -g` | debug floor | +| `o1` | `-O1` | light optimization | +| `o2` | `-O2` | common release default | +| `o3` | `-O3` | **current default** (CMake `Release`) | +| `ofast` | `-Ofast` | `-O3` + `-ffast-math` (single flag) | +| `o3_native` | `-O3 -march=native` | architecture-tuned | +| `o3_native_lto` | `-O3 -march=native -flto` | + whole-program LTO | +| `ofast_native_lto` | `-Ofast -march=native -flto` | the "max" setting | + +All variants share `-DNDEBUG`; the `-O` level is the variable under test. + +## Results + +Measured on the Apple M2 host above. Times are per-solve (small, n=800) and per +solve / per setup (large, n=2500), averaged over the reps shown. Ratios are +relative to the `-O3` default. + +| Variant | small solve (s) | × vs `-O3` | large solve (s) | × vs `-O3` | large setup (s) | × vs `-O3` | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | +| `-O0` | 0.086789 | 2.87× | 0.834060 | 2.82× | 4.244841 | 2.96× | +| `-O1` | 0.031020 | 1.03× | 0.293860 | 0.99× | 1.438983 | 1.00× | +| `-O2` | 0.030336 | 1.00× | 0.294022 | 1.00× | 1.400835 | 0.98× | +| `-O3` (def) | 0.030268 | 1.00× | 0.295519 | 1.00× | 1.434966 | 1.00× | +| `-Ofast` | **0.021072** | **0.70×** | **0.210061** | **0.71×** | 1.768622 | 1.23× | +| `-O3 -march=native` | 0.030308 | 1.00× | 0.294269 | 1.00× | 1.447293 | 1.01× | +| `-O3 -march=native -flto` | 0.030423 | 1.00× | 0.293481 | 0.99× | 1.444066 | 1.01× | +| `-Ofast -march=native -flto` | **0.020922** | **0.69×** | **0.209276** | **0.71×** | **1.422635** | **0.99×** | + +All variants report the same objective values (`small = -0.130387`, +`large = -0.129698`) and identical status/residuals to within machine precision — +no variant changes the answer. + +### End-to-end (Python wrapper) + +Rebuilding the wheel (default `-O3` vs `-OSQP_OPT_FAST_MATH=ON`) and timing a +box-constrained solve through `marinholab.solvers.osqp.Solver` on the same host: + +| Build | avg solve / rep (n=800) | +| --- | ---: | +| default (`-O3`) | ~397 ms | +| `OSQP_OPT_FAST_MATH=ON` | ~381 ms | + +The end-to-end gain (~4%) is smaller than the C-core gain (~30%) because the +Python wrapper spends a large share of each call converting the dense `Eigen` +Hessian (`O(n²)`) to CSC, which is not affected by `-ffast-math`. For solves that +are dominated by many ADMM iterations (larger `n`, tighter tolerances, repeated +warm-started calls in a control loop), the relative benefit of the opt-in flag +grows. + +## Findings + +1. **`-O3` is already the sweet spot.** `-O2` and `-O1` are within noise of + `-O3`; `-O0` is ~3× slower. There is nothing to gain by changing the + optimization level from the current `-O3`. + +2. **`-march=native` and `-flto` add nothing measurable here.** The ADMM loop + and the factorization are memory-bound enough that architecture-specific + tuning and link-time optimization do not help on this workload. (This also + matches the project's existing choice to keep LTO off in the `.deb` build for + reproducibility.) `-march=native` additionally breaks the manylinux + portability of the wheel, so it is not appropriate to enable by default. + +3. **`-ffast-math` is the real lever, worth ~25–30% in the solver core.** + It enables the fast-math floating-point contract, which lets the compiler + reassociate and vectorize the ADMM inner-loop arithmetic. Two subtleties + verified experimentally: + * The vendored OSQP/qdldl CMake files **append** an `-O3` after any flag you + inject, and in GCC/Clang the *last* `-O` wins. A bare `-Ofast` therefore + gets overridden by the trailing `-O3` and does nothing (measured: + `-Ofast -O3 -O3` ≈ baseline). `-ffast-math`, however, is independent of the + `-O` level and **does** survive the appended `-O3`. + * The flag must reach the *vendored* C code, not just the wrapper. Setting it + on the base `CMAKE_C_FLAGS`/`CMAKE_CXX_FLAGS` before `add_subdirectory(osqp)` + propagates it into OSQP and qdldl (verified via the generated + `compile_commands.json`). + +4. **It is numerically safe for this package.** `OSQP` is an iterative solver run + to a tolerance; `-ffast-math` does not change the reported solutions in the + test suite or the example (answers are identical, residuals differ only at + ~1e-12–1e-14 level). All 46 tests pass on both the default and the fast-math + build. + +## Change made + +Added an opt-in CMake option in `CMakeLists.txt` (default **OFF**, so the +shipped wheel and CI are byte-for-byte the IEEE-conformant `-O3` build): + +```cmake +option(OSQP_OPT_FAST_MATH "Enable fast-math (non-IEEE) optimizations in the OSQP core." OFF) +``` + +When ON it appends `-ffast-math` (or `/fp:fast` on MSVC) to the base C/CXX +flags before the OSQP subdirectory is added, so it reaches OSQP, qdldl, and the +wrapper. A consumer can enable it in either build path: + +```console +# C++ build +cmake -B build -GNinja -DCMAKE_BUILD_TYPE=Release -DOSQP_OPT_FAST_MATH=ON + +# Python wheel +CMAKE_ARGS="-DOSQP_OPT_FAST_MATH=ON" python setup.py bdist_wheel +``` + +> Note on the Python build: `setup.py` reuses its `build/temp/` CMake cache +> across `bdist_wheel` invocations, and CMake `option()` does not reset a +> variable that is already in the cache. To flip the flag between two wheel +> builds, delete `build/` (or the `build/temp/…/_core/` cache) first; otherwise +> the first value wins. + +## How to reproduce + +```console +cd solver-osqp +git submodule update --init --recursive + +# Build + run the C-core benchmark for a flag variant (see bench/build.sh for +# the full list): +./bench/build.sh o3 # -> bench/bin/o3 +./bench/bin/o3 # prints RESULT ... lines + +# Build + run every variant and aggregate a table: +./bench/run.sh +./bench/aggregate.py +``` + +The harness lives in `bench/`: + +* `bench/osqp_bench.c` — the benchmark (dense-SPD QP, cold-start solves). +* `bench/build.sh` — compiles the OSQP/qdldl C core with a chosen flag set. +* `bench/run.sh` — runs every built variant, saving raw output to `bench/results/`. +* `bench/aggregate.py` — collapses `bench/results/*.txt` into the comparison table. +* `bench/scan_flags.py` — prints the effective optimization flags per component + from a CMake `compile_commands.json` (used to verify the CMake change). + +`bench/bin/`, `bench/gen/`, and `bench/results/` are build artifacts and are +git-ignored. diff --git a/CMakeLists.txt b/CMakeLists.txt index ef8e53d..48f55c6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -49,6 +49,28 @@ set(OSQP_CODEGEN FALSE CACHE BOOL "x" FORCE) # FetchContent. Point that at the vendored submodule so no network access is # needed at configure time (reproducible, offline-friendly builds). set(FETCHCONTENT_SOURCE_DIR_QDLDL "${CMAKE_CURRENT_SOURCE_DIR}/qdldl" CACHE STRING "x") + +# Opt-in fast-math. Relaxes IEEE-754 (allows -ffast-math / /fp:fast), which the +# ADMM inner loop benefits from. See BENCHMARK.md for the numbers. OFF by +# default so the shipped wheel stays IEEE-conformant; a consumer that can +# tolerate the (negligible for QP solving) precision change can build with +# -DOSQP_OPT_FAST_MATH=ON to get a meaningful speed-up. +# +# The flag is appended to the *base* C/CXX flags before the OSQP subdirectory +# is added, so it propagates into the vendored OSQP and qdldl (whose CMake +# files append an optimization level afterwards). -ffast-math is independent of +# the -O level, so it survives that append; a bare -Ofast would not. +option(OSQP_OPT_FAST_MATH "Enable fast-math (non-IEEE) optimizations in the OSQP core." OFF) +if(OSQP_OPT_FAST_MATH) + if(MSVC) + set(_SOLVER_OSQP_FAST_MATH_FLAGS "/fp:fast") + else() + set(_SOLVER_OSQP_FAST_MATH_FLAGS "-ffast-math") + endif() + string(APPEND CMAKE_C_FLAGS " ${_SOLVER_OSQP_FAST_MATH_FLAGS}") + string(APPEND CMAKE_CXX_FLAGS " ${_SOLVER_OSQP_FAST_MATH_FLAGS}") +endif() + add_subdirectory(osqp) # The Solver/Configuration implementation. Both the pybind11 module and the diff --git a/bench/aggregate.py b/bench/aggregate.py new file mode 100644 index 0000000..f659d87 --- /dev/null +++ b/bench/aggregate.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python3 +"""Aggregate bench/results/*.txt into a comparison table (vs the -O3 baseline).""" +import os + +HERE = os.path.dirname(os.path.abspath(__file__)) +RES = os.path.join(HERE, "results") + + +def parse(path): + d = {} + for line in open(path): + if not line.startswith("RESULT"): + continue + toks = line.split() + name = toks[1] + rec = d.setdefault(name, {}) + for t in toks[2:]: + if "=" in t: + k, v = t.split("=", 1) + rec[k] = v + return d + + +order = ["o0", "o1", "o2", "o3", "ofast", "o3_native", "o3_native_lto", "ofast_native_lto"] +base = parse(os.path.join(RES, "o3.txt")) +bs = float(base["small"]["solve_time_avg"]) +bl = float(base["large"]["solve_time_avg"]) +bu = float(base["large"]["setup_time"]) + +print(f"{'variant':18} {'small solve/s':>13} {'vs -O3':>7} {'large solve/s':>13} {'vs -O3':>7} {'large setup/s':>13} {'vs -O3':>7}") +for v in order: + d = parse(os.path.join(RES, v + ".txt")) + so = float(d["small"]["solve_time_avg"]) + ls = float(d["large"]["solve_time_avg"]) + lu = float(d["large"]["setup_time"]) + print(f"{v:18} {so:13.6f} {so/bs:6.3f}x {ls:13.6f} {ls/bl:6.3f}x {lu:13.6f} {lu/bu:6.3f}x") diff --git a/bench/build.sh b/bench/build.sh new file mode 100755 index 0000000..7cde4a5 --- /dev/null +++ b/bench/build.sh @@ -0,0 +1,171 @@ +#!/usr/bin/env bash +# +# Builds the OSQP optimization benchmark (bench/osqp_bench.c) with a chosen set +# of optimization flags. The same OSQP + qdldl C sources that the project links +# against are compiled here, so only the compiler optimization flags vary +# between variants. +# +# Usage: +# ./bench/build.sh +# +# Variants: +# o0 -O0 -g (debug, reference floor) +# o1 -O1 +# o2 -O2 +# o3 -O3 (current default: CMake "Release") +# ofast -Ofast +# o3_native -O3 -march=native +# o3_native_lto -O3 -march=native -flto +# ofast_native_lto -Ofast -march=native -flto +# +# The binary is written to bench/bin/. +# +# All sources are C, so they are compiled with the same include layout and +# type configuration (double precision, 64-bit indexing, builtin algebra) that +# the project's CMake build produces. The generated headers +# (osqp_configure.h / qdldl_types.h / qdldl_version.h) are emitted under +# bench/gen so the build needs no CMake. +# +# -DNDEBUG is kept constant across variants so the only thing that changes is +# the optimization level itself (debug asserts are otherwise disabled by +# -O2+ in most toolchains, and we want a clean isolation). + +set -euo pipefail + +REPO="$(cd "$(dirname "$0")/.." && pwd)" +OSQP="$REPO/osqp" +QDLDL="$REPO/qdldl" +BENCH="$REPO/bench" +GEN="$BENCH/gen" +BIN="$BENCH/bin" + +CC="${CC:-cc}" +ARCH_FLAG="" +if [ "$(uname -m)" = "arm64" ]; then + ARCH_FLAG="-arch arm64" +fi + +VARIANT="${1:-}" +if [ -z "$VARIANT" ]; then + echo "usage: $0 " >&2 + echo "variants: o0 o1 o2 o3 ofast o3_native o3_native_lto ofast_native_lto" >&2 + exit 2 +fi +shift || true + +case "$VARIANT" in + o0) OPTFLAGS="-O0 -g" ;; + o1) OPTFLAGS="-O1" ;; + o2) OPTFLAGS="-O2" ;; + o3) OPTFLAGS="-O3" ;; + ofast) OPTFLAGS="-Ofast" ;; + o3_native) OPTFLAGS="-O3 -march=native" ;; + o3_native_lto) OPTFLAGS="-O3 -march=native -flto" ;; + ofast_native_lto) OPTFLAGS="-Ofast -march=native -flto" ;; + *) echo "unknown variant: $VARIANT" >&2; exit 2 ;; +esac +OPTFLAGS="$OPTFLAGS -DNDEBUG" + +mkdir -p "$BIN" "$GEN/osqp/include/public" "$GEN/qdldl/include" + +# ---- Generate the configuration headers the real build produces ---------- + +cat > "$GEN/osqp/include/public/osqp_configure.h" <<'EOF' +#ifndef OSQP_CONFIGURE_H +# define OSQP_CONFIGURE_H +/* OSQP_ENABLE_DEBUG */ +/* #undef OSQP_ENABLE_DEBUG */ +/* #undef IS_LINUX */ +#define IS_MAC +/* #undef IS_WINDOWS */ +#define OSQP_ALGEBRA_BUILTIN +/* #undef OSQP_ALGEBRA_MKL */ +/* #undef OSQP_ALGEBRA_CUDA */ +/* #undef OSQP_CODEGEN */ +/* #undef OSQP_PROFILER_ANNOTATIONS */ +#define OSQP_ENABLE_DERIVATIVES +/* #undef OSQP_EMBEDDED_MODE */ +/* #undef OSQP_CUSTOM_MEMORY */ +#define OSQP_ENABLE_PRINTING +/* #undef OSQP_CUSTOM_PRINTING */ +#define OSQP_ENABLE_PROFILING +#define OSQP_ENABLE_INTERRUPT +/* #undef OSQP_USE_FLOAT */ +#define OSQP_USE_LONG +/* #undef OSQP_PACK_SETTINGS */ +#endif /* ifndef OSQP_CONFIGURE_H */ +EOF + +cat > "$GEN/qdldl/include/qdldl_types.h" <<'EOF' +#ifndef QDLDL_TYPES_H +#define QDLDL_TYPES_H +#include +typedef long long QDLDL_int; +typedef double QDLDL_float; +typedef unsigned char QDLDL_bool; +#define QDLDL_INT_MAX LLONG_MAX +/* #undef QDLDL_FLOAT */ +#define QDLDL_LONG +#endif /* ifndef QDLDL_TYPES_H */ +EOF + +cat > "$GEN/qdldl/include/qdldl_version.h" <<'EOF' +#ifndef QDLDL_VERSION_H_ +#define QDLDL_VERSION_H_ +#define QDLDL_VERSION_MAJOR 0 +#define QDLDL_VERSION_MINOR 1 +#define QDLDL_VERSION_PATCH 8 +#endif +EOF + +# ---- Source list (identical to the project's static OSQP + qdldl build) ---- +SRC=( + "$BENCH/osqp_bench.c" + "$OSQP/src/osqp_api.c" + "$OSQP/src/auxil.c" + "$OSQP/src/derivative.c" + "$OSQP/src/error.c" + "$OSQP/src/interrupt_unix.c" + "$OSQP/src/polish.c" + "$OSQP/src/scaling.c" + "$OSQP/src/timing_macos.c" + "$OSQP/src/util.c" + "$OSQP/algebra/_common/csc_math.c" + "$OSQP/algebra/_common/csc_utils.c" + "$OSQP/algebra/_common/kkt.c" + "$OSQP/algebra/_common/lin_sys/qdldl/qdldl_interface.c" + "$OSQP/algebra/_common/lin_sys/qdldl/amd/src/amd_1.c" + "$OSQP/algebra/_common/lin_sys/qdldl/amd/src/amd_2.c" + "$OSQP/algebra/_common/lin_sys/qdldl/amd/src/amd_aat.c" + "$OSQP/algebra/_common/lin_sys/qdldl/amd/src/amd_control.c" + "$OSQP/algebra/_common/lin_sys/qdldl/amd/src/amd_defaults.c" + "$OSQP/algebra/_common/lin_sys/qdldl/amd/src/amd_info.c" + "$OSQP/algebra/_common/lin_sys/qdldl/amd/src/amd_order.c" + "$OSQP/algebra/_common/lin_sys/qdldl/amd/src/amd_post_tree.c" + "$OSQP/algebra/_common/lin_sys/qdldl/amd/src/amd_postorder.c" + "$OSQP/algebra/_common/lin_sys/qdldl/amd/src/amd_preprocess.c" + "$OSQP/algebra/_common/lin_sys/qdldl/amd/src/amd_valid.c" + "$OSQP/algebra/_common/lin_sys/qdldl/amd/src/SuiteSparse_config.c" + "$OSQP/algebra/builtin/algebra_libs.c" + "$OSQP/algebra/builtin/matrix.c" + "$OSQP/algebra/builtin/vector.c" + "$QDLDL/src/qdldl.c" +) + +INC=( + -I"$GEN/osqp/include/public" + -I"$OSQP/include/public" + -I"$OSQP/include/private" + -I"$OSQP/algebra/_common" + -I"$OSQP/algebra/builtin" + -I"$OSQP/algebra/_common/lin_sys/qdldl" + -I"$OSQP/algebra/_common/lin_sys/qdldl/amd/include" + -I"$QDLDL/include" + -I"$GEN/qdldl/include" +) + +OUT="$BIN/$VARIANT" +echo "Building $VARIANT with: $OPTFLAGS" +# shellcheck disable=SC2086 +"$CC" $OPTFLAGS $ARCH_FLAG -fPIC -std=c99 "${INC[@]}" -o "$OUT" "${SRC[@]}" -lm +echo "Built $OUT" diff --git a/bench/osqp_bench.c b/bench/osqp_bench.c new file mode 100644 index 0000000..6d83176 --- /dev/null +++ b/bench/osqp_bench.c @@ -0,0 +1,289 @@ +/* + * Optimization benchmark for the OSQP solver core used by + * marinholab-solvers-osqp. + * + * What it measures + * ---------------- + * The package's hot path is OSQP itself: the ADMM iteration loop plus the + * built-in algebra (CSC matrix products) and the qdldl/AMD LDL^t factorizer + * that solves the KKT linear system. This benchmark compiles exactly those + * C sources (see build.sh) with a chosen set of compiler flags, so the only + * thing that varies between runs is the optimization level. + * + * Two problem workloads are run: + * - "small" (n ~ 800) : steady-state ADMM throughput + * - "large" (n ~ 2500) : factorization-heavy setup timing (qdldl scaling) + * + * The Hessian P is dense and SPD (P = M'M + n*I), which mirrors how the + * Python wrapper feeds OSQP: it converts a *dense* Eigen Hessian to CSC, so + * in practice the top-left block of the KKT system is dense. Box constraints + * plus a few equality rows are added so the KKT system has a realistic + * structure. + * + * Solves are cold-started (warm_starting = 0) so the iteration count is + * stable and the ADMM loop does substantial work on every call. + * + * Output + * ------ + * One machine-readable "RESULT ..." line per metric, e.g. + * + * RESULT small setup_time=0.012345s + * RESULT small solve_time_avg=0.004321s reps=400 + * RESULT small iters_avg=50.0 + * RESULT small obj_val=-0.128031 status=solved + * + * The objective value lets a human (or script) verify that a different + * optimization level did not change the solution. + */ + +#include + +#include +#include +#include +#include +#include +#include + +/* ------------------------------------------------------------------ */ +/* Deterministic PRNG (splitmix64) so every variant sees identical data. */ +/* ------------------------------------------------------------------ */ +static uint64_t g_st; + +static uint64_t sm64(void) +{ + uint64_t z = (g_st += 0x9E3779B97F4A7C15ULL); + z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ULL; + z = (z ^ (z >> 27)) * 0x94D049BB133111EBULL; + return z ^ (z >> 31); +} + +static double runit(void) /* uniform in [0, 1) */ +{ + return (double)(sm64() >> 11) * (1.0 / 9007199254740992.0); +} + +static double now_s(void) +{ + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return (double)ts.tv_sec + 1e-9 * (double)ts.tv_nsec; +} + +/* ------------------------------------------------------------------ */ +/* Problem construction. */ +/* ------------------------------------------------------------------ */ + +struct problem +{ + OSQPCscMatrix P, A; + OSQPFloat *q, *l, *u; + int n, m; +}; + +static struct problem make_problem(int n, int m_box, int m_eq, uint64_t seed) +{ + struct problem pr; + int m = m_box + m_eq; + pr.n = n; + pr.m = m; + g_st = seed; + + /* ---- P = M'M + n*I (dense, SPD), upper triangle in CSC ---- */ + int nnzP = n * (n + 1) / 2; + pr.P.m = pr.P.n = n; + pr.P.nzmax = nnzP; + pr.P.nz = -1; /* CSC */ + pr.P.owned = 0; + pr.P.p = (OSQPInt *)malloc(sizeof(OSQPInt) * (n + 1)); + pr.P.i = (OSQPInt *)malloc(sizeof(OSQPInt) * nnzP); + pr.P.x = (OSQPFloat *)malloc(sizeof(OSQPFloat) * nnzP); + + double **M = (double **)malloc(sizeof(double *) * n); + for (int r = 0; r < n; r++) + { + M[r] = (double *)malloc(sizeof(double) * n); + for (int c = 0; c < n; c++) + M[r][c] = runit() * 2.0 - 1.0; /* uniform in [-1, 1) */ + } + int k = 0; + for (int c = 0; c < n; c++) + { + pr.P.p[c] = k; + for (int r = 0; r <= c; r++) + { + double acc = (r == c) ? (double)n : 0.0; + for (int t = 0; t < n; t++) + acc += M[t][r] * M[t][c]; + pr.P.i[k] = r; + pr.P.x[k] = acc; + k++; + } + } + pr.P.p[n] = k; + for (int r = 0; r < n; r++) + free(M[r]); + free(M); + + pr.q = (OSQPFloat *)malloc(sizeof(OSQPFloat) * n); + for (int i = 0; i < n; i++) + pr.q[i] = runit() * 2.0 - 1.0; + + /* ---- A: m_box box rows (A[r,r]=1, rq); + free(pr->l); + free(pr->u); + free(pr->P.p); + free(pr->P.i); + free(pr->P.x); + free(pr->A.p); + free(pr->A.i); + free(pr->A.x); +} + +/* ------------------------------------------------------------------ */ +/* Run one workload and report. */ +/* ------------------------------------------------------------------ */ +static int run_workload(const char *name, struct problem *pr, int warmup, int reps) +{ + OSQPSettings *s = OSQPSettings_new(); + osqp_set_default_settings(s); + s->verbose = 0; + s->warm_starting = 0; /* stable iteration count across cold solves */ + s->polishing = 0; + s->eps_abs = 1e-6; + s->eps_rel = 1e-6; + s->max_iter = 5000; + + OSQPSolver *sol = NULL; + double t0 = now_s(); + OSQPInt rc = osqp_setup(&sol, &pr->P, pr->q, &pr->A, pr->l, pr->u, pr->m, pr->n, s); + double setup_time = now_s() - t0; + if (rc != 0) + { + fprintf(stderr, "%s: osqp_setup failed (%s)\n", name, osqp_error_message(rc)); + OSQPSettings_free(s); + return 1; + } + + for (int i = 0; i < warmup; i++) + osqp_solve(sol); + + long long iters_sum = 0; + double total = 0.0; + OSQPFloat last_obj = 0.0; + for (int i = 0; i < reps; i++) + { + double a = now_s(); + osqp_solve(sol); + total += now_s() - a; + iters_sum += (long long)sol->info->iter; + last_obj = sol->info->obj_val; + } + + printf("RESULT %s n=%d m=%d\n", name, pr->n, pr->m); + printf("RESULT %s status=%s obj_val=%.6f prim_res=%.3e dual_res=%.3e\n", + name, sol->info->status, last_obj, sol->info->prim_res, sol->info->dual_res); + printf("RESULT %s setup_time=%.6f s\n", name, setup_time); + printf("RESULT %s solve_time_avg=%.6f s reps=%d warmup=%d\n", + name, total / reps, reps, warmup); + printf("RESULT %s iters_avg=%.2f\n", name, (double)iters_sum / reps); + + osqp_cleanup(sol); + OSQPSettings_free(s); + return 0; +} + +int main(int argc, char **argv) +{ + int small_n = 800, small_eq = 8; + int large_n = 2500, large_eq = 16; + int reps = 300, large_reps = 40, warmup = 20, large_warmup = 5; + uint64_t seed = 42; + + for (int i = 1; i < argc; i++) + { + if (strcmp(argv[i], "-small-n") == 0) small_n = atoi(argv[++i]); + else if (strcmp(argv[i], "-small-eq") == 0) small_eq = atoi(argv[++i]); + else if (strcmp(argv[i], "-large-n") == 0) large_n = atoi(argv[++i]); + else if (strcmp(argv[i], "-large-eq") == 0) large_eq = atoi(argv[++i]); + else if (strcmp(argv[i], "-reps") == 0) reps = atoi(argv[++i]); + else if (strcmp(argv[i], "-large-reps") == 0) large_reps = atoi(argv[++i]); + else if (strcmp(argv[i], "-seed") == 0) seed = (uint64_t)strtoull(argv[++i], NULL, 10); + else if (strcmp(argv[i], "-skip-large") == 0) large_n = 0; + } + + int ok = 0; + struct problem small = make_problem(small_n, small_n, small_eq, seed); + ok |= run_workload("small", &small, warmup, reps); + free_problem(&small); + + if (large_n > 0) + { + struct problem large = make_problem(large_n, large_n, large_eq, seed + 1); + ok |= run_workload("large", &large, large_warmup, large_reps); + free_problem(&large); + } + return ok; +} diff --git a/bench/run.sh b/bench/run.sh new file mode 100755 index 0000000..37a086d --- /dev/null +++ b/bench/run.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +# Runs every built benchmark variant and captures its RESULT lines. +# Usage: ./bench/run.sh [variant ...] (default: all variants in bench/bin) +set -euo pipefail +BENCH="$(cd "$(dirname "$0")" && pwd)" +BIN="$BENCH/bin" +OUT="$BENCH/results" +mkdir -p "$OUT" + +variants=("$@") +if [ "${#variants[@]}" -eq 0 ]; then + variants=(o0 o1 o2 o3 ofast o3_native o3_native_lto ofast_native_lto) +fi + +for v in "${variants[@]}"; do + exe="$BIN/$v" + if [ ! -x "$exe" ]; then + echo "missing $exe, building..." >&2 + "$BENCH/build.sh" "$v" >/dev/null + fi + echo "=== running $v ===" >&2 + "$exe" | tee "$OUT/$v.txt" +done +echo "All done. Results in $OUT/" >&2 diff --git a/bench/scan_flags.py b/bench/scan_flags.py new file mode 100644 index 0000000..c876ba9 --- /dev/null +++ b/bench/scan_flags.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python3 +"""Print the effective optimization flags per component from a CMake +`compile_commands.json`. Useful to verify that an optimization flag (e.g. +`-ffast-math`) actually reached the vendored OSQP / qdldl / wrapper. + +Usage: + python bench/scan_flags.py [ ...] +""" +import json +import sys + + +def scan(path): + out = {} + for e in json.load(open(path)): + f = e["file"] + if "solver-osqp/src/core" in f: + tag = "WRAPPER" + elif "solver-osqp/osqp/" in f: + tag = "OSQP" + elif "qdldl/src/qdldl.c" in f: + tag = "QDLDL" + else: + tag = "OTHER" + toks = e["command"].split() + opt = [x for x in toks + if x in ("-O3", "-O2", "-O1", "-Ofast", "-O0") + or x == "-ffast-math" + or x.startswith("-march") + or "flto" in x] + out.setdefault(tag, set()).update(opt) + return {k: sorted(v) for k, v in out.items()} + + +paths = sys.argv[1:] or ["build/compile_commands.json"] +for p in paths: + try: + s = scan(p) + except OSError: + print(f"!! {p} not found") + continue + print(f"--- {p} ---") + for k in ("OSQP", "QDLDL", "WRAPPER"): + print(f" {k:8} {s.get(k, [])}") From 1c20f23070fa32dc14ef8c870e39613ddba9dba9 Mon Sep 17 00:00:00 2001 From: Murilo Marinho Date: Thu, 1 Oct 2026 18:29:51 +0100 Subject: [PATCH 2/2] Add GCC 16 g++ data point to BENCHMARK.md (fast-math is slower under GCC) Cross-compiler result: clang 21 is ~30% faster with -Ofast/-ffast-math, but GCC 16 is ~15-18% slower. This is the strongest argument for keeping OSQP_OPT_FAST_MATH opt-in and OFF by default. Co-authored-by: openhands --- BENCHMARK.md | 65 +++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 49 insertions(+), 16 deletions(-) diff --git a/BENCHMARK.md b/BENCHMARK.md index 508041e..7302791 100644 --- a/BENCHMARK.md +++ b/BENCHMARK.md @@ -17,35 +17,42 @@ CMake option). So the shipped wheel is already built at `-O3` everywhere. * Going from `-O3` to `-O2`/`-O1` is **not** a speedup, and `-march=native` and `-flto` give **no measurable gain** on this workload. -* The one flag that moves the needle is **`-ffast-math`** (a.k.a. the - fast-math part of `-Ofast`): it makes the C OSQP core ~**25–30% faster** in - the steady-state ADMM loop. Because the dense-matrix→CSC conversion in the - wrapper is a large, fast-math-insensitive cost, the end-to-end Python solve - time improves by a more modest ~**4–8%**. +* The one flag that *can* move the needle is **`-ffast-math`** (a.k.a. the + fast-math part of `-Ofast`). Its effect is **compiler-specific**: + * **Apple clang 21** — ~**25–30% faster** C core in the steady-state ADMM + loop. Because the wrapper's dense-matrix→CSC conversion is a large, + fast-math-insensitive cost, the end-to-end Python solve improves by a more + modest ~**4–8%**. + * **GCC 16** — *slower* (~**15–18% worse**). GCC's fast-math reassociation + hurts the ADMM loop on this workload. + This cross-compiler disagreement is the single strongest argument for **not** + turning fast-math on by default. * `-ffast-math` relaxes IEEE-754. It does **not** change the solutions this package produces in the tests or example (answers are identical to the `-O3` build, with only machine-precision-level differences in residuals), because OSQP is an iterative solver that runs to a tolerance. **Decision:** keep the default build at the IEEE-conformant `-O3` (matching -OSQP's own default), and expose the fast-math option as an **opt-in** CMake -flag, `OSQP_OPT_FAST_MATH` (OFF by default), so a consumer who can tolerate the -relaxed floating-point contract can opt into the speedup without changing the -shipped wheel. +OSQP's own default, and the best cross-compiler choice), and expose fast-math as +an **opt-in** CMake flag, `OSQP_OPT_FAST_MATH` (OFF by default). A consumer on a +clang toolchain who can tolerate the relaxed floating-point contract can opt in +to the speedup; the shipped wheel and CI are unaffected. ## Environment | Item | Value | | --- | --- | | Host | Apple M2, arm64 (macOS) | -| Compiler | Apple clang 21 (`cc`; `gcc`/`g++` are clang on macOS) | +| Compiler (clang) | Apple clang 21 (`cc`; on macOS the default `gcc`/`g++` are clang) | +| Compiler (gcc) | Homebrew `gcc-16` / `g++-16` (GNU 16.2.0) — a real g++/gcc data point | | OSQP | submodule `1572ae06` (≈ v1.0.0) | | qdldl | submodule `138fdac58` (v0.1.8) | | pybind11 | submodule `d03662f0` (v3.0) | | Python | 3.12 | The numbers below are from this host; relative ratios are what matter, and the -harness is included so results can be re-produced on any machine. +harness is included so results can be re-produced on any machine. Where the two +compilers disagree (fast-math), both are reported. ## Methodology @@ -88,7 +95,9 @@ All variants share `-DNDEBUG`; the `-O` level is the variable under test. Measured on the Apple M2 host above. Times are per-solve (small, n=800) and per solve / per setup (large, n=2500), averaged over the reps shown. Ratios are -relative to the `-O3` default. +relative to each compiler's `-O3` default. + +### Apple clang 21 | Variant | small solve (s) | × vs `-O3` | large solve (s) | × vs `-O3` | large setup (s) | × vs `-O3` | | --- | ---: | ---: | ---: | ---: | ---: | ---: | @@ -101,6 +110,25 @@ relative to the `-O3` default. | `-O3 -march=native -flto` | 0.030423 | 1.00× | 0.293481 | 0.99× | 1.444066 | 1.01× | | `-Ofast -march=native -flto` | **0.020922** | **0.69×** | **0.209276** | **0.71×** | **1.422635** | **0.99×** | +### GCC 16.2 (`gcc-16` / `g++-16`) + +| Variant | small solve (s) | × vs `-O3` | large solve (s) | × vs `-O3` | +| --- | ---: | ---: | ---: | ---: | +| `-O0` | 0.095282 | 3.68× | 0.911597 | 3.57× | +| `-O1` | 0.027455 | 1.06× | 0.266503 | 1.04× | +| `-O2` | 0.025833 | 1.00× | 0.253390 | 0.99× | +| `-O3` (def) | 0.025879 | 1.00× | 0.255678 | 1.00× | +| `-Ofast` | **0.030271** | **1.17×** | **0.294474** | **1.15×** | +| `-O3 -march=native` | 0.025973 | 1.00× | 0.252121 | 0.99× | +| `-O3 -march=native -flto` | 0.026017 | 1.00× | 0.253238 | 0.99× | +| `-Ofast -march=native -flto` | **0.030488** | **1.18×** | **0.292212** | **1.14×** | + +**Cross-compiler note.** Both compilers agree that `-O3` is the best non-fast +level and that `-march=native`/`-flto` do nothing. They *disagree* on +fast-math: clang 21 is ~30% faster, while **GCC 16 is ~15–18% slower** with +`-Ofast`/`-ffast-math`. So fast-math is a compiler-specific gamble, not a +universal win — reinforcing that it should stay opt-in and OFF by default. + All variants report the same objective values (`small = -0.130387`, `large = -0.129698`) and identical status/residuals to within machine precision — no variant changes the answer. @@ -135,10 +163,12 @@ grows. reproducibility.) `-march=native` additionally breaks the manylinux portability of the wheel, so it is not appropriate to enable by default. -3. **`-ffast-math` is the real lever, worth ~25–30% in the solver core.** - It enables the fast-math floating-point contract, which lets the compiler - reassociate and vectorize the ADMM inner-loop arithmetic. Two subtleties - verified experimentally: +3. **Fast-math is the only real lever — but it is compiler-specific.** It + enables the fast-math floating-point contract, which lets the compiler + reassociate and vectorize the ADMM inner-loop arithmetic. On this host + **clang 21 is ~30% faster** with it, while **GCC 16 is ~15–18% slower** — + so it is a gamble, not a universal win. Two subtleties verified + experimentally: * The vendored OSQP/qdldl CMake files **append** an `-O3` after any flag you inject, and in GCC/Clang the *last* `-O` wins. A bare `-Ofast` therefore gets overridden by the trailing `-O3` and does nothing (measured: @@ -196,6 +226,9 @@ git submodule update --init --recursive # Build + run every variant and aggregate a table: ./bench/run.sh ./bench/aggregate.py + +# Use a different compiler (e.g. a real g++/gcc) by exporting CC: +CC=/opt/homebrew/bin/gcc-16 ./bench/build.sh o3 ``` The harness lives in `bench/`: