# mip-heuristics ```{include} ../README.md :relative-docs: docs/ :relative-images: :start-after: :end-before: ``` % Drawn by figures/make_figure.py from the v0.1.0 headline runs; one copy per colour mode. ```{figure} figures/primal-gap-light.svg :figclass: only-light :align: center :width: 640px :alt: Primal gap over time on lectsched-5-obj: with the heuristics a solution comes at 1.6 s and the gap falls in steps to 0.47, primal integral 0.63; HiGHS alone has none until 413 s and ends at 0.76, primal integral 1.62. Primal gap over 600 s on the `mipfeas` instance `lectsched-5-obj`, HiGHS with and without the heuristics (v0.1.0, 16 workers): the shaded area is each run's primal integral times 600 s. ``` ```{figure} figures/primal-gap-dark.svg :figclass: only-dark :align: center :width: 640px :alt: Primal gap over time on lectsched-5-obj: with the heuristics a solution comes at 1.6 s and the gap falls in steps to 0.47, primal integral 0.63; HiGHS alone has none until 413 s and ends at 0.76, primal integral 1.62. Primal gap over 600 s on the `mipfeas` instance `lectsched-5-obj`, HiGHS with and without the heuristics (v0.1.0, 16 workers): the shaded area is each run's primal integral times 600 s. ``` ```{include} ../README.md :relative-docs: docs/ :relative-images: :start-after: ``` ```{toctree} :hidden: quickref options results method cpp ``` # Quick reference How to call the patched HiGHS, as a command or a library, and what it prints. ## Terminal ```bash # Build the highs command line, ./build/bin/highs (fetches and patches HiGHS v1.16.0) git clone https://github.com/spoorendonk/mip-heuristics && cd mip-heuristics cmake -B build -DCMAKE_BUILD_TYPE=Release cmake --build build -j$(nproc) # Install for Python: import mip_heuristics (compiles the patched HiGHS) pip install git+https://github.com/spoorendonk/mip-heuristics # Solve a file at the shipped defaults ./build/bin/highs model.mps # Set options in an options file: they are not command-line flags printf 'mip_heuristic_fj_effort = 0\n' > run.opts ./build/bin/highs --options_file run.opts model.mps # Trace the heuristics: [Heur] and [HeurSol] lines printf 'log_dev_level = 3\n' > trace.opts ./build/bin/highs --options_file trace.opts model.mps # Stop after the heuristics, before the root LP printf 'mip_heuristic_presolve_only = true\n' > presolve.opts ./build/bin/highs --options_file presolve.opts model.mps # HiGHS's own flags: time limit, seed, threads, solution file ./build/bin/highs --time_limit 60 --random_seed 1 --threads 8 --solution_file model.sol model.mps # The command line's flags ./build/bin/highs --help # Every option of the patch and its default (also the Options page) python -c "import mip_heuristics.options as o; print(o.heuristic_options())" ``` - **Output**: a patched binary prints `mip-heuristics patch active` as the third line of its log. At `log_dev_level = 3`, one `[Heur]` line per heuristic dispatch and one `[HeurSol]` line per point the heuristics' pool accepts, which need not become HiGHS's incumbent; early FJ logs plain lines. - **Exit status**: HiGHS's run status: `0` ok, `1` warning (a time, iteration or solution limit; on a MIP, `mip_heuristic_presolve_only` ends at the solution limit, or with `0` when presolve solves it), `255` error, such as an unknown option key, an unknown flag or a flag without its value. A flag value the parser rejects exits with the parser's own code. ## Python ```python import numpy as np from mip_heuristics import Highs from mip_heuristics.options import heuristic_options # Solve from arrays: min -x0 - 2 x1 s.t. x0 + x1 <= 3.5, x0 and x1 integer in [0, 3] cost, lo, up = np.array([-1.0, -2.0]), np.zeros(2), np.full(2, 3.0) row_lo, row_up = np.array([-np.inf]), np.array([3.5]) start, index, value = np.array([0, 1]), np.array([0, 0]), np.array([1.0, 1.0]) integer = np.array([1, 1]) h = Highs() # 2 columns, 1 row, 2 nonzeros, the matrix column-wise (1), minimize (1), offset 0 h.passModel( 2, 1, 2, 1, 1, 0.0, cost, lo, up, row_lo, row_up, start, index, value, integer ) h.run() print(h.getModelStatus(), h.getSolution().col_value) # Solve a file, any option: the patch's or HiGHS's h = Highs() h.setOptionValue("mip_heuristic_fj_effort", 0.0) h.readModel("model.mps") h.run() print(h.getModelStatus(), h.getInfo().objective_function_value) # Every option of the patch and its default print(heuristic_options()) ``` ## C++ Link the target `highs` this project builds: the [C++ reference](cpp.md#using-it-from-cmake) has the CMake lines, and the API of `mip_heuristics_core`, the heuristics without the solver. Reference: [C++](cpp.md); all the docs as text: , . # Options The patch adds the options below to HiGHS; every other option is HiGHS's own ([HiGHS options](https://ergo-code.github.io/HiGHS/stable/options/definitions/)). - **Set them** in an options file (`highs --options_file run.opts model.mps`) or from Python (`h.setOptionValue("mip_heuristic_fj_effort", 0.0)`). Python has the same defaults; `mip_heuristics.options.heuristic_options()` lists them. - **Selection is the budget**: a heuristic runs only if its `mip_heuristic__effort` is above zero. FeasibilityJump also needs HiGHS's `mip_heuristic_run_feasibility_jump` left at `true`. - **Units**: effort and patience are multiples of `nnz << 10`, vanilla HiGHS's FeasibilityJump budget; `mip_heuristic_fpr_lp_effort` is a share of the RENS/RINS LP-iteration envelope instead. - **What each heuristic and feature does**: [Method](method.md). - **MPS** (`.mps`, and `.mps.gz` in a build with zlib): the column-oriented format, free or fixed ([spec](https://www.ibm.com/docs/en/icos/22.1.1?topic=standard-records-in-mps-format)). - **CPLEX LP** (`.lp`): the algebraic, row-oriented format ([spec](https://www.ibm.com/docs/en/icos/22.1.1?topic=cplex-lp-file-format-algebraic-representation)). The listing is what the solver writes for these options (`Highs::writeOptions`), in options-file form; a test keeps it equal. ```text # Per-worker effort budget multiplier for the FeasibilityJump presolve # heuristic # [type: double, advanced: false, range: [0, 1e+06], default: 0.3317] mip_heuristic_fj_effort = 0.3317 # Effort budget multiplier for the FPR presolve heuristic # [type: double, advanced: false, range: [0, 1e+06], default: 3.161] mip_heuristic_fpr_effort = 3.161 # Effort budget multiplier for the LocalMIP presolve heuristic # [type: double, advanced: false, range: [0, 1e+06], default: 3.2865] mip_heuristic_local_mip_effort = 3.2865 # Effort budget multiplier for the Scylla presolve heuristic. The default 0 # disables it, since on the 233-instance benchmark it produced no accepted # incumbent while dispatching on every solve. Raising it runs Scylla with no # rebuild # [type: double, advanced: false, range: [0, 1e+06], default: 0] mip_heuristic_scylla_effort = 0 # Effort budget multiplier for the ruin-and-repair LNS presolve heuristic, # after Scylla in the chain, which ruins the pool's best point and repairs it # with FeasibilityJump under an objective cutoff. The default 0 disables it # [type: double, advanced: false, range: [0, 1e+06], default: 0] mip_heuristic_ruin_effort = 0 # Effort budget multiplier for the recombination presolve heuristic, last in # the chain, which recombines pairs of pool points and runs FeasibilityJump # from the offspring. The default 0 disables it # [type: double, advanced: false, range: [0, 1e+06], default: 0] mip_heuristic_recombine_effort = 0 # Effort budget multiplier for the dive-time fpr_lp heuristic, as a share of # the lesser of the remaining RENS/RINS LP-iteration headroom and 80 x # mip_heuristic_effort x nnz<<10 (nnz<<12 at HiGHS's default 0.05). The # default 0 disables fpr_lp, since RENS/RINS dominate it inside the shared # envelope and it costs primal integral where it engages without finding a # solution. 1.0 takes the whole slice and larger values take more # [type: double, advanced: false, range: [0, 1e+06], default: 0] mip_heuristic_fpr_lp_effort = 0 # Per-worker patience for the FeasibilityJump presolve heuristic: # improvement-free effort tolerated before it gives up, as a multiple of # nnz<<10, the same unit as this heuristic's effort option, clamped to a # quarter of it (0 disables the gate) # [type: double, advanced: false, range: [0, 1e+06], default: 0] mip_heuristic_fj_patience = 0 # Patience for the FPR presolve heuristic: improvement-free effort tolerated # before it gives up, as a multiple of nnz<<10, the same unit as this # heuristic's effort option, clamped to a quarter of it (0 disables the gate) # [type: double, advanced: false, range: [0, 1e+06], default: 0.3372] mip_heuristic_fpr_patience = 0.3372 # Patience for the LocalMIP presolve heuristic: improvement-free effort # tolerated before it gives up, as a multiple of nnz<<10, the same unit as # this heuristic's effort option, clamped to a quarter of it (0 disables the # gate) # [type: double, advanced: false, range: [0, 1e+06], default: 3.1943] mip_heuristic_local_mip_patience = 3.1943 # Patience for the Scylla presolve heuristic: improvement-free effort # tolerated before it gives up, as a multiple of nnz<<10, the same unit as # this heuristic's effort option, clamped to a quarter of it (0 disables the # gate) # [type: double, advanced: false, range: [0, 1e+06], default: 0] mip_heuristic_scylla_patience = 0 # Patience for the ruin-and-repair LNS presolve heuristic: improvement-free # effort tolerated before it gives up, as a multiple of nnz<<10, the same unit # as this heuristic's effort option, clamped to a quarter of it (0 disables # the gate) # [type: double, advanced: false, range: [0, 1e+06], default: 0] mip_heuristic_ruin_patience = 0 # Patience for the recombination presolve heuristic: improvement-free effort # tolerated before it gives up, as a multiple of nnz<<10, the same unit as # this heuristic's effort option, clamped to a quarter of it (0 disables the # gate) # [type: double, advanced: false, range: [0, 1e+06], default: 0] mip_heuristic_recombine_patience = 0 # Exit the solve after the presolve heuristic chain, before the root LP, # keeping the incumbent it found # [type: bool, advanced: false, range: {false, true}, default: false] mip_heuristic_presolve_only = false # Run no presolve heuristic in a RINS/RENS sub-MIP, which inherits every other # option from its parent. The default false runs the chain there as in the # top-level solve, except while long-lived slots run (mip_heuristic_long_lived # on, mip_heuristic_long_lived_threads above 0 and a slot heuristic enabled), # when a sub-MIP skips it too # [type: bool, advanced: false, range: {false, true}, default: false] mip_heuristic_skip_submip_chain = false # Point a rebuilt FeasibilityJump presolve worker restarts from. 0 the default # (the pool's best). 1 best (the same for FJ). 2 hybrid (Local-MIP v2's hybrid # restart, each column the best's value or a random one within its bounds, # 50/50) # [type: integer, advanced: false, range: {0, 2}, default: 0] mip_heuristic_fj_restart = 0 # Point a rebuilt LocalMIP presolve worker restarts from. 0 the default (a # pool draw, perturbed). 1 best (the pool's best, unperturbed). 2 hybrid # (Local-MIP v2's hybrid restart, each column the best's value or a random one # within its bounds, 50/50) # [type: integer, advanced: false, range: {0, 2}, default: 0] mip_heuristic_local_mip_restart = 0 # Start a rebuilt LocalMIP presolve worker's weights, with probability one # half, at draws from {1, 2} instead of 1 (CP-SAT's restart weight draw) # [type: bool, advanced: false, range: {false, true}, default: false] mip_heuristic_local_mip_restart_weights = false # Run FeasibilityJump's slots, long-lived ones included, as cuOpt's lane # table, slot s being lane s mod 16. A slot's first worker starts as its lane # does, by cuOpt's seeding rule (with a point, lane 0 and odd lanes keep it # and the other even lanes drop it) and from the lane's structural start where # the model supports it (greedy covering on lanes 3 and 10, exact-k then # covering then the precedence start on lane 8, the affine equality start on # lanes 2 and 4, and on lanes 1, 9, 11, 12 and 15 the structural completion, # with covering around it and the affine equality start after them on lane 11, # ambiguous-lock bounds and covering before it on lane 12 and the ordinal # midpoint after it on lane 15), and on every lane but 0 and 8, on a # fixed-charge flow network, cuOpt's network start after those and before the # affine start # [type: bool, advanced: false, range: {false, true}, default: true] mip_heuristic_fj_personas = true # Give the last worker of the dive-time fpr_lp heuristic, when it has two or # more, to FeasibilityJump started from the dive's LP solution rounded at # random (cuOpt's LP start persona) instead of an LP-FPR arm, when its budget # holds FJ's callback period (about 488 nonzeros per worker at the default # share). Needs mip_heuristic_fpr_lp_effort above 0 # [type: bool, advanced: false, range: {false, true}, default: false] mip_heuristic_fj_lp_persona = false # Give the FeasibilityJump workers on cuOpt's exchange lanes (slots 1, 7, 11 # and 15 mod 16, long-lived ones included) cuOpt's cardinality exchange, a # compound move that sets one member of a uniform binary equality row from 1 # to 0 and another from 0 to 1 so the row's count is kept # [type: bool, advanced: false, range: {false, true}, default: true] mip_heuristic_fj_exchange = true # Run the Scylla presolve heuristic's pump as cuOpt's: an L1 distance # projection blended with the objective, its weight reset on each improvement, # a PDLP tolerance set by how integral the last LP point is, a warm start from # the rounding, and fix-and-propagate with repair on every chain. Needs # mip_heuristic_scylla_effort above 0 # [type: bool, advanced: false, range: {false, true}, default: false] mip_heuristic_scylla_cuopt_pump = false # Give each Scylla presolve worker a PDLP of its own, so no worker waits for # another's LP solve or rounds a peer's last LP point, at one copy of the LP # per worker. A build with the GPU PDLP ignores it and keeps one shared # instance. Needs mip_heuristic_scylla_effort above 0 # [type: bool, advanced: false, range: {false, true}, default: false] mip_heuristic_scylla_pdlp_per_worker = false # Keep the Scylla presolve heuristic's pump going after the first incumbent, # as cuOpt does: its projection LP takes the row objective <= best - max(0.1% # of |best|, 1e-7), moved down as the incumbent improves, and a pump whose LP # is infeasible under the cut stops. Needs mip_heuristic_scylla_effort above 0 # [type: bool, advanced: false, range: {false, true}, default: false] mip_heuristic_scylla_objective_cut = false # Race a GPU FeasibilityJump worker beside the whole solve in long-lived mode. # Needs a MIP_HEURISTICS_CUDA build, mip_heuristic_long_lived on and # mip_heuristic_presolve_only off. Any other run warns and runs # FeasibilityJump on the CPU only # [type: bool, advanced: false, range: {false, true}, default: false] mip_heuristic_fj_gpu = false # Effort budget multiplier for FeasibilityJump on the original model while # presolve runs, per worker (one on a thread of its own, and with # mip_heuristic_fj_personas, FeasibilityJump in the chain and at least 7 # threads a second on lane 6), as a multiple of the original model's nnz<<10. # It stops when presolve returns, and its best solution becomes the MIP start, # kept in original space as the answer unless the solve finds better. The # default 0 disables it # [type: double, advanced: false, range: [0, 1e+06], default: 0] mip_heuristic_early_fj_effort = 0 # Keep an owner for heuristics that run on threads of their own beside branch # and bound for the main MIP's whole solve, whose solutions the solving thread # installs at HiGHS's external-solution poll points and once more at the end. # mip_heuristic_long_lived_threads sets how many such threads run. The default # false allocates nothing and starts no thread # [type: bool, advanced: false, range: {false, true}, default: false] mip_heuristic_long_lived = false # Number of long-lived heuristic threads beside branch and bound, dealt # round-robin to FeasibilityJump, LocalMIP, Scylla (not beside the whole-solve # GPU race in a MIP_HEURISTICS_CUDA build), ruin-and-repair and recombine, # those whose effort option is above zero, from the end of the presolve # heuristics to the end of the solve, paused across each restart. Needs # mip_heuristic_long_lived. The default 0 starts none # [type: integer, advanced: false, range: {0, 2147483647}, default: 0] mip_heuristic_long_lived_threads = 0 ``` # Results `mipfeas`: 233 MIPLIB 2017 instances, 600 s, one seed, 16 workers, CPU build on an AMD Ryzen 9 3950X (16 cores). Release v0.1.0 on HiGHS v1.15.1 against an unpatched HiGHS v1.15.1 at default options. - **Metric**: the primal integral, divided by the time limit, so it lies in [0, 2] ([Problem](index.md#problem)), with the benchmark's own reference objectives. - **Comparison**: paired per instance on the log ratio at shift 0.001, patched over vanilla, so below 1 means the heuristics are ahead. The interval is the normal 95% one. - **Sets**: the tuning set is the 90 instances the defaults were tuned on, and held-out is the other 143. Unseen is held-out less the 48 also used to choose between the final candidates. ## Known issues - Later releases, from v0.1.10 on HiGHS v1.16.0, are not in this table. - The runs use 16 workers and are not deterministic, so a rerun reproduces the result, not the logs. - The tuning set was drawn from instances some heuristic solves alone, so its row overstates the gain. The held-out row is the fair estimate. ## Primal integral | Instances | n | Primal-integral ratio | 95% CI | Better / tied / worse | |---|---|---|---|---| | All | 233 | 0.763 | [0.684, 0.852] | 114 / 24 / 95 | | Held-out | 143 | 0.871 | [0.782, 0.970] | 63 / 19 / 61 | | Tuning | 90 | 0.619 | [0.496, 0.772] | 51 / 5 / 34 | | Unseen | 95 | 0.861 | [0.746, 0.994] | 43 / 11 / 41 | ## Reproduce ```bash # The tables above, from the committed per-run CSV (a test runs this) python3 bench/analyze_results.py --check README.md docs/results.md # The runs, at the release in a build tree of their own: the MIPLIB instances once per machine (3.5 GB), then both arms at 600 s, about 77 hours git checkout v0.1.0 cmake -B build-v0.1.0 -DCMAKE_BUILD_TYPE=Release cmake --build build-v0.1.0 -j$(nproc) bash bench/download_miplib.sh export MIPFEAS_BINARY=$PWD/build-v0.1.0/bin/highs MIPFEAS_VANILLA_BINARY=/path/to/unpatched/highs-1.15.1 bench/run_mipfeas.sh next 24 bench/run_mipfeas.sh status # The per-run CSV, from those runs, back on main git checkout main python3 bench/analyze_results.py bench/results/mipfeas --configs all vanilla --time-limit 600 --csv bench/headline/runs.csv ``` # Method The heuristics run inside HiGHS's MIP solve, after presolve and before the root LP, as a fixed chain: FeasibilityJump → FPR → LocalMIP → Scylla → ruin-and-repair → recombination. Each entry runs on parallel workers (HiGHS's `threads`) that share one solution pool and hand every improving point to HiGHS; the chain runs again after a restart that re-enters the pre-root heuristics, and inside a RENS/RINS sub-MIP unless `mip_heuristic_skip_submip_chain` or long-lived threads are on. The pool holds 10 points and refuses a twin of an entry's integer columns unless it is better; when full, it admits a dominated point within 10% of the best that is far from every entry. The algorithms show each heuristic's core and leave out guards, tolerances and caps, which are in the source. ## Budget - **Unit**: effort is a multiple of $\text{nnz} \ll 10$, vanilla HiGHS's own FeasibilityJump limit, so `effort = 1.0` is one vanilla FJ budget. FJ's option sizes each worker; the others size the whole dispatch, split over the workers. Each heuristic counts its own work (FJ steps, coefficient accesses, PDLP iterations × nnz). - **Patience** is the improvement-free effort a heuristic tolerates before it stops, `mip_heuristic__patience`, in the same unit and clamped to a quarter of the budget; `0` means no gate. A better best objective resets it, and for FJ also a new fewest count of violated rows. - **Selection is the budget**: a heuristic runs only if its `mip_heuristic__effort` is above zero (FJ also needs HiGHS's `mip_heuristic_run_feasibility_jump`). - **Defaults** run FJ, FPR and LocalMIP: effort `0.3317`, `3.161`, `3.2865`; patience `0`, `0.3372`, `3.1943`. - **Deadline**: the solve's `time_limit` also stops the chain. Every worker polls it, and an entry reached after it is skipped. ## FeasibilityJump A weighted local search that jumps one variable at a time to the value minimising its weighted violation (Luteberget and Sartor, 2023). With $\nu_i(x) = \max\{0,\ L_i - a_i^\top x,\ a_i^\top x - U_i\}$ and $D_j$ the column's domain ($[l_j, u_j]$, its integers for $j \in I$), the jump value and score of column $j$ are $$ t_j = \arg\min_{v \in D_j,\ v \neq x_j} \sum_i w_i\, \nu_i\big(x + (v - x_j) e_j\big), \qquad s_j = \sum_i w_i \big[\nu_i(x) - \nu_i(x + (t_j - x_j) e_j)\big] - w_0\, c_j (t_j - x_j). $$ ```{pcode} \begin{algorithm} \caption{FeasibilityJump} \begin{algorithmic} \Procedure{FJ}{$x^0$, seed} \State $x \gets x^0$; $w_i \gets 1$ on every row, $w_0 \gets 0$; compute $t_j, s_j$ for every column \While{budget, patience and deadline are left} \If{$x$ is feasible and better} \State offer $x$ \EndIf \If{some $s_j > 0$} \State $j \gets$ the best of 25 sampled columns with $s_j > 0$ \Else \State $w_i \gets w_i + 1$ on every violated row ($w_0 \gets w_0 + 1$ if none) \Comment{local minimum} \State $j \gets$ the best column of one random violated row (a random column if none) \EndIf \State $x_j \gets t_j$; update $t$ and $s$ of the columns sharing a row with $j$ \EndWhile \EndProcedure \end{algorithmic} \end{algorithm} ``` - It is HiGHS's own FJ (`feasibilityjump.hh`), on N workers with distinct seeds. By default every worker but those of lane 0 takes its lane's start, weights and moves ([FJ personas](#fj-personas)); the pseudocode above and the start rule here are lane 0's, and every worker's with `mip_heuristic_fj_personas` and `mip_heuristic_fj_exchange` both `false`. A worker starts from the pool's best point, else HiGHS's incumbent, else FJ's bound start; a worker that finishes or stalls is rebuilt from the pool. - The patch makes FJ's `solve()` resumable, so the budget, patience and deadline are read at upstream's progress callback, every 500000 effort units. - A worker's patience reads FJ's own effort since its last improvement, which also restarts at a new fewest-violated-rows count, so falling violations keep a worker alive before its first feasible point. ## FPR (fix-propagate-repair) A depth-first fix-and-propagate search that repairs the partial assignment at every node propagation refutes (Salvagnin, Roberti and Fischetti, 2025). Propagation keeps each row's activity range; a repair shifts a column's whole domain by $s$ to reduce the summed violation: $$ m_i = \sum_{a_{ij} > 0} a_{ij} l_j + \sum_{a_{ij} < 0} a_{ij} u_j, \quad M_i = \sum_{a_{ij} > 0} a_{ij} u_j + \sum_{a_{ij} < 0} a_{ij} l_j, \quad \text{viol}_i = \max\{0,\ m_i - U_i,\ L_i - M_i\}. $$ ```{pcode} \begin{algorithm} \caption{FPR} \begin{algorithmic} \Procedure{FPR}{$P$, variable order $\pi$, value rule, mode} \State $E \gets$ the propagation engine on $P$; $Q \gets [\text{root}]$ \While{$Q \neq \emptyset$ and budget and deadline are left} \State $(x_j = v, \text{mark}) \gets$ pop($Q$); backtrack $E$ to the mark \State infeasible $\gets$ fix $x_j = v$ in $E$ \Comment{refuted if a row of $j$ has no completion} \If{not infeasible and the mode propagates} \State infeasible $\gets$ propagate($E$) \EndIf \If{infeasible and the mode repairs} \State infeasible $\gets$ repair walk: shift domains in $E$ \EndIf \If{infeasible and the mode backtracks} \State \textbf{continue} \EndIf \State $j' \gets$ the next unfixed integer column in $\pi$; \textbf{break} if none \Comment{leaf} \If{the mode backtracks} \State push($Q$, $x_{j'} =$ the other value) \EndIf \State push($Q$, $x_{j'} =$ value rule($j'$, $E$)) \EndWhile \State $x \gets$ the current point, unfixed columns filled \If{a leaf was reached and $x$ violates a row} \State $x \gets$ RepairSearch($x$) in that mode, WalkSAT($x$) in a repairing mode \EndIf \State \Return $x$, and whether a leaf was reached and every row holds \Comment{Scylla rounds from $x$ either way} \EndProcedure \end{algorithmic} \end{algorithm} ``` - The presolve chain rotates eight LP-free (variable order, mode) pairs over workers and attempts, across the paper's modes `dfs`, `dfsrep`, `dive`, `diveprop` and RepairSearch; the orders are computed once per dispatch. - The repair walk's damage and best-state comparison sum violation magnitudes, not counts of violated rows. - A dive mode carries an unrepaired node to the bottom, and every leaf gets the continuous fill and the leaf-time repair; one final check over every row decides feasibility. ## LocalMIP A two-level-scored local search with mixed tight, breakthrough and lift moves (Lin, Zou and Cai, 2024). The mixed tight move sets $x_j \leftarrow x_j + \Delta_{ij}$, $\Delta_{ij} = (b_i - a_i^\top x)/a_{ij}$, clipped to $[l_j, u_j]$ and rounded for an integer. An operation is ranked by its progress score: $\pm w_i$ when row $i$ becomes satisfied or violated, or stays violated but moves nearer or farther (the authors' code; the paper gives the last case $w_i/2$), $\pm w_0$ when the objective improves or worsens. Ties go to the bonus score, over the rows the move takes into the strict interior: $$ \text{bonus}(op) = w_0\,[\,c^\top x^{op} < c^\top x^*\,] + \sum_i w_i\,[\,a_i^\top x \ge b_i,\ a_i^\top x^{op} < b_i\,]. $$ ```{pcode} \begin{algorithm} \caption{LocalMIP} \begin{algorithmic} \Procedure{LocalMIP}{$x^0$} \State $x \gets x^0$; $w_0 \gets 1$; $w_i \gets 1$ \While{budget, patience and deadline are left} \If{$x$ is feasible} \State lift moves: improve $c^\top x$ while every row stays satisfied \If{$c^\top x < c^\top x^*$} \State $x^* \gets x$; offer $x^*$ \EndIf \EndIf \State $C \gets$ positive tight moves in violated rows (and breakthrough moves once $x^*$ exists) \If{$C = \emptyset$} \State $C \gets$ positive tight moves in satisfied rows \EndIf \If{$C = \emptyset$} \State $C \gets$ positive Boolean flips \EndIf \If{$C = \emptyset$} \If{with probability $1 - 0.0003$} \State $w_0 \gets w_0 + 1$ if $x$ is feasible, else $w_i \gets w_i + 1$ on every violated row \Else \State smooth: $w_0 \gets w_0 - 1$ if $c^\top x < c^\top x^*$, and $w_i \gets w_i - 1$ on every satisfied row \EndIf \State $C \gets$ breakthrough moves $\cup$ tight moves of one random violated row \EndIf \State $x \gets op(x)$ for the $op \in C$ of the highest progress, then bonus, tabu moves excluded \EndWhile \EndProcedure \end{algorithmic} \end{algorithm} ``` - A worker starts from the pool's best point, else HiGHS's incumbent, else the paper's zero start followed by a greedy construction sweep. - Rows and candidate columns are sampled (best from multiple selections) as in the authors' code, where Algorithm 2 enumerates them; an integer tight move rounds by the two-sided row's state. - Beyond the paper: a perturbation after a feasible plateau, an easy-move fallback when no phase yields a move, and a restart after 200000 steps without improvement, alternately from the best and from a random point. ## Scylla A feasibility pump on approximate LP solutions from PDLP, rounded by fix-and-propagate (Mexi et al., 2023). Round $K$ projects with the blended cost below ($\alpha = 0.9$; $\Delta_j = 1 - 2\hat x_j$ on a binary, $\operatorname{sign}(\bar x_j - \hat x_j)$ on a general integer, $0$ on a continuous column) and tightens PDLP's tolerance from $\varepsilon^{(1)} = 10^{-2}$: $$ \hat c = \alpha^K \frac{\sqrt{|I|}}{\lVert c \rVert}\, c + (1 - \alpha^K)\, \Delta(\hat x), \qquad \varepsilon^{(K+1)} = \max\{0.98\,\varepsilon^{(K)}, 10^{-8}\}. $$ ```{pcode} \begin{algorithm} \caption{Scylla chain, one of N} \begin{algorithmic} \State $\hat c \gets c$; $\varepsilon \gets 10^{-2}$; $K \gets 1$ \While{budget, patience and deadline are left} \If{a peer holds the PDLP} \State $\hat x \gets$ FPR(the last completed iterate); offer $\hat x$ if it is MIP-feasible \State \textbf{continue} \Comment{no pump advance} \EndIf \State $\bar x \gets$ PDLP($\min \hat c^\top x$ over the LP relaxation, warm start, tolerance $\varepsilon$) \If{$\bar x$ is MIP-feasible} \State offer $\bar x$; \textbf{continue} \EndIf \State $\hat x \gets$ FPR($\bar x$) \Comment{the value rule rounds toward $\bar x$} \If{$\hat x$ is MIP-feasible} \State offer $\hat x$ \Comment{$\hat x$ is FPR's point even when its repair failed} \EndIf \If{$\hat x$ repeats one of the last 3 roundings} \State perturb $\hat x$ \EndIf \State $\hat c \gets$ the blended cost above; $\varepsilon \gets \max\{0.98\,\varepsilon, 10^{-8}\}$; $K \gets K + 1$ \EndWhile \end{algorithmic} \end{algorithm} ``` - The N chains share one PDLP (HiGHS's cuPDLP-C); a chain that finds it busy rounds the last completed iterate, a bounded number of times in a row. The instance runs without presolve, so a warm start lands on the right columns. - Each chain rounds with FPR's LP value rule on $\bar x$, under one of four (variable order, mode) pairs; the orders are computed once per dispatch. - A failed rounding still advances the pump (perturbation, decay, new cost). A feasible point is offered and the chain keeps pumping, where the paper's pump returns. ## Ruin-and-repair A large-neighborhood search that ruins integer columns of the best point and repairs with FJ under an objective cutoff, after NVIDIA cuOpt's CPU LNS worker. After $n$ repairs without improvement it ruins $k(n)$ of the $|I|$ non-fixed integer columns, and gives the repair $b(k)$ seconds of FJ effort at $2\cdot 10^8$ per second: $$ k(n) = \min\Big\{|I|,\ \min\{40, \max\{6, \lfloor |I|/200 \rfloor\}\} \cdot \big(1 + \min\{\lfloor n/6 \rfloor, 6\}\big)\Big\}, \qquad b(k) = \min\{2,\ 0.15 + 0.02\,k\}. $$ ```{pcode} \begin{algorithm} \caption{Ruin-and-repair worker} \begin{algorithmic} \State $x^* \gets$ none; $n \gets 0$ \While{budget, patience and deadline are left} \State $p \gets$ the pool's best point if it is feasible, else $x^*$ \If{$x^*$ is none} \State $G \gets \emptyset$; $x^* \gets p$; $n \gets 0$ \ElsIf{$c^\top p < c^\top x^* - 10^{-7}$} \State $G \gets \{j \in I : p_j \neq x^*_j\}$; $x^* \gets p$; $n \gets 0$ \EndIf \State $R \gets$ shuffle($G$), then uniform non-fixed integer columns, until $|R| = k(n)$ \State $y \gets x^*$; for $j \in R$, $y_j \gets p_j$ or a uniform integer in $[l_j, u_j]$, by a fair coin \State $x \gets$ FJ($y$) with the row $c^\top x \le c^\top x^* - 2 \max\{\text{feastol}, |c^\top x^*|\,\epsilon_{\text{mach}}\}$ and budget $b(|R|)$ \If{$x$ is feasible} \State $x^* \gets x$; offer $x$; $n \gets 0$ \Else \State $n \gets n + 1$ \EndIf \EndWhile \end{algorithmic} \end{algorithm} ``` - The repair is bounded by FJ effort rather than seconds, so a `threads=1` run replays. - The objective bound is a hard row in FJ's model, where cuOpt scores the objective against its best; cuOpt's geometric repair for disjunctive models is not carried over. - Guidance and the coin compare against the worker's best, not FJ's last assignment; each repair is a fresh FJ search with fresh weights. ## Recombination Recombines two pool points, chosen by a bandit over three recombiners, then runs FJ from the offspring, after NVIDIA cuOpt's diversity manager. The bandit is UCB with recency-weighted estimates; the bound-prop recombiner keeps at most $m$ of the $d$ differing integer columns free, adapting $m$ when $d > m$: $$ a_t = \arg\max_a\ q_a + \sqrt{2 \ln t / n_a}, \quad q_a \leftarrow q_a + 0.05\,(r - q_a), \qquad m \leftarrow \begin{cases} \lceil 1.1\,m \rceil & \text{offspring equals a parent}\\ \lfloor 0.99\,m \rfloor & \text{otherwise} \end{cases} \in [20, 10^4]. $$ ```{pcode} \begin{algorithm} \caption{Recombination worker} \begin{algorithmic} \While{budget, patience and deadline are left and the pool holds at least 2 points} \State $(a, b) \gets$ a tournament draw from the pool; $z^* \gets$ the pool's best objective \State arm $\gets$ UCB over bound-prop, guided crossover and neighborhood crossover \State $y \gets$ arm($a$, $b$) \If{the recombination failed} \State reward(arm, 0); \textbf{continue} \EndIf \If{$y$ is feasible} \State offer $y$ \EndIf \State $x \gets$ FJ($y$) for 1 s ($y$ feasible) or 0.5 s ($y$ infeasible) of effort; offer $x$ \State reward(arm, $r(z, z^*)$), $z$ the best objective of $y$ and FJ's points that are feasible \Comment{8 beats $z^*$; up to 4 if better than both parents and near $z^*$} \EndWhile \end{algorithmic} \end{algorithm} ``` - Bound-prop fixes the integer columns where $a$ and $b$ agree, frees $\min\{d, m\}$ random differing ones and fixes the rest at $a$, then propagates; FPR (DFS, fill, WalkSAT repair) completes the free columns toward $(a + b)/2$, where cuOpt probes each column once and solves an LP over the continuous ones. - Every limit is FJ effort at $2\cdot 10^8$ per second, not wall time, and the reward is normalised by effort, so a worker replays from its seed; one bandit per worker, with no lock. The reward reads the pool's best at the draw, before FJ's offers raise it. - The patience is effort without a better best objective, not cuOpt's rounds without a top-three entry. ## Features | Feature | Default | Options | |---|---|---| | [Scylla](#scylla) | `0` | `mip_heuristic_scylla_effort`, `mip_heuristic_scylla_patience` | | [Ruin-and-repair](#ruin-and-repair) | `0` | `mip_heuristic_ruin_effort`, `mip_heuristic_ruin_patience` | | [Recombination](#recombination) | `0` | `mip_heuristic_recombine_effort`, `mip_heuristic_recombine_patience` | | `fpr_lp` at dive time | `0` | `mip_heuristic_fpr_lp_effort` | | Early FJ over presolve | `0` | `mip_heuristic_early_fj_effort` | | Long-lived threads beside branch and bound | `false`, `0` | `mip_heuristic_long_lived`, `mip_heuristic_long_lived_threads` | | FJ personas | `true` | `mip_heuristic_fj_personas` | | FJ cardinality exchange | `true` | `mip_heuristic_fj_exchange` | | FJ LP persona | `false` | `mip_heuristic_fj_lp_persona` | | Scylla's cuOpt-style pump | `false` | `mip_heuristic_scylla_cuopt_pump` | | Per-worker PDLP | `false` | `mip_heuristic_scylla_pdlp_per_worker` | | Scylla's objective cut | `false` | `mip_heuristic_scylla_objective_cut` | | GPU FJ race | `false` | `mip_heuristic_fj_gpu` | | Restart points | `0`, `0`, `false` | `mip_heuristic_fj_restart`, `mip_heuristic_local_mip_restart`, `mip_heuristic_local_mip_restart_weights` | | Sub-MIP chain skip | `false` | `mip_heuristic_skip_submip_chain` | | Presolve-only | `false` | `mip_heuristic_presolve_only` | ### Chain entries off by default - Scylla: on the [benchmark](results.md) it dispatched on every solve and produced no accepted incumbent. - Ruin-and-repair: on instances HiGHS does not solve it was active on some and gained nothing; its primal integral was within noise of the default's. - Recombination: on the same instances it was active on some and gained nothing; its primal integral was slightly worse than the default's. ### `fpr_lp` at dive time - FPR with the paper's LP-based strategies, at the end of B&B's dive heuristics after RENS/RINS, inside their LP-iteration envelope. Worker $w$ runs arm $w \bmod 10$, each bound to a reference point: the analytic center, a zero-objective vertex or the dive's LP point. - A call is sized from the envelope's headroom and charges its LP iterations and effort back to it, with $\sigma$ the option, $e$ = `mip_heuristic_effort`, $T$ and $T_h$ the total and heuristic LP iterations: $$ B = \sigma \cdot \min\big\{\text{nnz}\,(e\,T + 10^4 - T_h),\ 80\, e\, (\text{nnz} \ll 10)\big\}. $$ - It skips while more than one B&B worker searches, so under HiGHS's default `parallel=choose` it runs only during the search's single-worker ramp-up. - Off by default. Alone, with RENS and RINS off, it found accepted incumbents on 20% of the 49 instances. ### Early FJ over presolve - One FJ worker on the original model, on a thread of its own, while HiGHS presolves, and with `mip_heuristic_fj_personas`, FJ in the chain and at least 7 threads a second one on lane 6; the best point becomes the MIP start if it is feasible in the presolved space too. - Off by default. With effort `1.0`, one worker and the lane table off, on a few instances with a slow presolve, its primal integral was well below the default run's; final bounds were unchanged. ### Long-lived threads beside branch and bound - `mip_heuristic_long_lived_threads` threads, on top of `threads`, from the end of the chain to the end of the solve, dealt round-robin over the enabled FJ, LocalMIP, Scylla, ruin and recombination entries. - Each runs one worker that restarts from one pool spanning the solve, which also takes B&B's incumbents; HiGHS installs their points at its external-solution poll points. While they run, RENS/RINS sub-MIPs skip their chain. - Over a solve: the slots start after the chain; at a restart they are joined, their points installed and the pool carried into the new presolved model, and they start again after its setup; at the end they are joined before postsolve. Only the solving thread installs points; a slot reads the presolved model in place, which nothing writes until a restart has joined the slots. The GPU race (below) pauses across restarts the same way. - Off by default: with two slots (one FJ, one LocalMIP), the primal integral was within noise of the default's on a CPU build and with the GPU race, and both lost optimality proofs the default reached within the limit. ### FJ personas - FJ slot $s$ runs cuOpt's CPU FJ lane $s \bmod 16$: the lane's start persona (covering, exact-k, precedence, affine equality, structural completion, fixed-charge network, p-median, unit commitment) on its first worker, where the model supports it. - Every worker of the slot also takes the lane's weight policy (smoothing, SAPS, donation, objective floor) and move policy (tabu, sampling, kicks, restores, perturbation, pair lift, compound repair, tight-row exchange). ### FJ cardinality exchange - On cuOpt's exchange lanes (slots 1, 7, 11 and 15 mod 16), a move that sets one binary of an exact-k row $\sum_{j \in R} x_j = k$ from 1 to 0 and another from 0 to 1, keeping the count; it is scored as FJ's weighted violation change over both columns' rows, less the objective term. ### FJ LP persona - With `fpr_lp` on and two or more workers, its last worker runs FJ from a random rounding of the dive's LP point instead of an LP-FPR arm, when the model has at most 8 million nonzeros and the worker's budget holds one FJ callback period. ### Scylla's cuOpt-style pump - The projection takes the exact L1 distance to the rounding $\tilde x$, through an auxiliary column $d_j \ge |x_j - \tilde x_j|$ per non-binary integer column, and the cost $(1 - a)\,\delta/\lVert\delta\rVert_2 + a\,c/\lVert c\rVert_2$, $\delta$ the distance's cost vector; $a$ starts at $0.99$, is multiplied by $0.9$ before each projection and is reset on an improvement. - PDLP's tolerance follows how integral $\bar x$ is; two cycle detectors run an FJ escape before a perturbation, and failed roundings earn FJ runs; FPR with repair rounds on every chain. - Off by default: on a GPU build its primal integral was within noise of the default pump's, and neither pump produced an improving incumbent. ### Per-worker PDLP - In a CPU PDLP build each Scylla chain gets its own PDLP instance, so every round is fresh, at one LP copy per worker; a GPU PDLP build keeps the shared one. ### Scylla's objective cut - Every projection LP, the pump's FJ runs and its rounding carry the row $c^\top x \le z^* - \max\{10^{-3}|z^*|, 10^{-7}\}$ below the pool's best $z^*$, moved down as it improves; a chain whose LP is infeasible under the cut stops. ### GPU FJ race - In a CUDA build's long-lived mode, one GPU worker running a cuOpt-style FJ races for the whole solve and offers into the long-lived pool; elsewhere the option warns and FJ runs on the CPU only. - Off by default, as long-lived mode is. ### Restart points - What a rebuilt FJ or LocalMIP worker restarts from: `0` the default (FJ the pool's best, LocalMIP a perturbed pool draw), `1` the pool's best unperturbed, `2` Local-MIP v2's hybrid (each column the best's value or a random one, 50/50). The LocalMIP weight draw starts a rebuilt worker's weights at draws from {1, 2} half the time. - LocalMIP's three arms showed no gap difference outside noise, presolve-only. At FJ's default patience of 0 a presolve FJ worker is rebuilt only when its search runs out of moves, when it has spent its own share of the budget while the dispatch runs on, or, on lanes 4, 8 and 12, when a find's lift from the equality-reduced model is rejected. ### Sub-MIP chain skip - A RENS/RINS sub-MIP copies its parent's options and so runs the chain on the sub-problem; on, it runs none. ### Presolve-only - The solve exits after the chain, before the root LP, keeping the chain's incumbent. A measurement mode, far cheaper than a full solve. ## References 1. **Salvagnin, Roberti, Fischetti (2025)** — *A fix-propagate-repair heuristic for mixed integer programming*. Mathematical Programming Computation, 17:111–139. DOI: [10.1007/s12532-024-00269-5](https://doi.org/10.1007/s12532-024-00269-5) — FPR and `fpr_lp`. 2. **Lin, Zou, Cai (2024)** — *An Efficient Local Search Solver for Mixed Integer Programming*. Proc. CP 2024, LIPIcs vol. 307, Article 19, pp. 19:1–19:19. DOI: [10.4230/LIPIcs.CP.2024.19](https://doi.org/10.4230/LIPIcs.CP.2024.19) — LocalMIP. 3. **Mexi, Besançon, Bolusani, Chmiela, Hoen, Gleixner (2023)** — *Scylla: a matrix-free fix-propagate-and-project heuristic for mixed-integer optimization*. OR Proceedings 2023, 57–63. DOI: [10.1007/978-3-031-58405-3_9](https://doi.org/10.1007/978-3-031-58405-3_9) — Scylla. 4. **Luteberget, Sartor (2023)** — *Feasibility Jump: an LP-free Lagrangian MIP heuristic*. Mathematical Programming Computation, 15:365–388. DOI: [10.1007/s12532-023-00234-8](https://doi.org/10.1007/s12532-023-00234-8) — FeasibilityJump. All four are open access under CC BY 4.0 and the PDFs are in [`docs/`](https://github.com/spoorendonk/mip-heuristics/tree/main/docs), which maps each paper to the source files that implement it. ## Related Projects - [**HiGHS**](https://github.com/ERGO-Code/HiGHS) — the solver these heuristics are compiled into, via a patched build of v1.16.0 - [**cuOpt**](https://github.com/NVIDIA/cuopt) — NVIDIA's GPU solver, with variants of LocalMIP and of the Scylla pump (arXiv:2510.20499) # C++ reference A caller of `highs` sets [options](options.md) and includes nothing of ours. The sections after *Using it from CMake* are for a caller of `mip_heuristics_core`, the heuristics without the solver: build the view with `make_problem`, receive what the workers find through a `SolutionSink`, and run one FJ or LocalMIP worker on a thread of your own with `run_until_stopped`. The contracts are in the headers' comments, which this page does not render: [`heuristic_context.h`](https://github.com/spoorendonk/mip-heuristics/blob/main/src/heuristic_context.h), [`solution_sink.h`](https://github.com/spoorendonk/mip-heuristics/blob/main/src/solution_sink.h), [`fj.h`](https://github.com/spoorendonk/mip-heuristics/blob/main/src/fj.h) and [`local_mip.h`](https://github.com/spoorendonk/mip-heuristics/blob/main/src/local_mip.h). ## Using it from CMake Build it inside your project and link `highs`, HiGHS v1.16.0 with the patch and the heuristics compiled in, static; `#include "Highs.h"` works as is: ```cmake include(FetchContent) FetchContent_Declare(mip_heuristics GIT_REPOSITORY https://github.com/spoorendonk/mip-heuristics.git GIT_TAG v0.1.12) FetchContent_MakeAvailable(mip_heuristics) target_link_libraries(my_solver PRIVATE highs) # the solver target_link_libraries(my_workers PRIVATE mip_heuristics_core) # the heuristics alone ``` - **Clone or submodule** in your source tree: `add_subdirectory(mip-heuristics)` replaces the `FetchContent` lines. - **First configure** clones and patches HiGHS: it needs network access. - **No `highs` of your own** (a `FetchContent` declaration or a target) before this one: FetchContent keeps the first declaration, without the patch. - **Nothing else registers**: no tests, lint or bench targets in your build; HiGHS's own extras (`highs-bin`, install rules) come along as upstream defines them. HiGHS's switches (`BUILD_TESTING`, `BUILD_SHARED_LIBS`, ...) are set in this project's scope only. - **Installed** (`cmake --install`): `highs::highs` and `highs::mip_heuristics_core` in HiGHS's `find_package(highs)` package; outside CMake, `pkg-config --static --libs highs`. - **HiGHS patches of your own**: [`MIP_HEURISTICS_EXTRA_HIGHS_PATCHES`](https://github.com/spoorendonk/mip-heuristics/blob/main/dev/development.md#as-a-subproject). ## The model view ```{doxygenfunction} make_problem ``` ```{doxygenstruct} ProblemView ``` ```{doxygenstruct} ProblemStorage ``` ```{doxygenstruct} ProblemError ``` ## Budget and execution ```{doxygenstruct} HeuristicBudget ``` ```{doxygenfunction} make_until_stopped_budget ``` ```{doxygenstruct} ExecutionContext ``` ```{doxygentypedef} RestartSource ``` ## Solutions ```{doxygenclass} SolutionSink ``` ```{doxygenfunction} make_solution_pool ``` ## Workers on your own threads ```{doxygenfunction} fj::run_until_stopped ``` ```{doxygenfunction} local_mip::run_until_stopped ``` ***************** Source Code Files ***************** This section contains source code files from the project repository. These files are included to provide implementation context and technical details that complement the documentation above. **Files included:** .. code-block:: text README.md fj.h heuristic_context.h local_mip.h solution_sink.h README.md ========= .. code-block:: markdown # mip-heuristics *Primal heuristics for mixed-integer programming* [![Docs](https://img.shields.io/badge/docs-spoorendonk.dk%2Fmip--heuristics-be123c.svg)](https://spoorendonk.dk/mip-heuristics/) [![arXiv](https://img.shields.io/badge/arXiv-2609.22938-b31b1b.svg)](https://arxiv.org/abs/2609.22938) [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.22837481.svg)](https://doi.org/10.5281/zenodo.22837481) [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://github.com/spoorendonk/mip-heuristics/blob/main/LICENSE) Primal heuristics for mixed-integer programming inside [HiGHS](https://github.com/ERGO-Code/HiGHS). FeasibilityJump, FPR, LocalMIP and Scylla, plus ruin-and-repair and recombination, run as one budgeted chain after presolve in a patched HiGHS v1.16.0. Use it as the `highs` command line, from Python, or as a C++ library. It accompanies [arXiv:2609.22938](https://arxiv.org/abs/2609.22938).

Primal gap over time on lectsched-5-obj: with the heuristics a solution comes at 1.6 s and the gap falls in steps to 0.47, primal integral 0.63; HiGHS alone has none until 413 s and ends at 0.76, primal integral 1.62.

Primal gap over 600 s on the mipfeas instance lectsched-5-obj: the shaded area is each run's primal integral times 600 s.

## Problem A mixed-integer program in HiGHS's form: $$ \min_x \; c^\top x \quad \text{s.t.} \quad L \le Ax \le U, \quad l \le x \le u, \quad x_j \in \mathbb{Z} \ (j \in I) $$ The heuristics look for a good feasible $x$ early. A run is scored by its primal integral $P = \frac{1}{T}\int_0^T \gamma(t)\,dt$, with $T$ the time limit and $\gamma(t)$ the primal gap of the incumbent at time $t$, as the `mipfeas` benchmark defines it: $\max\{0,\ (z - z^*) / \max(|z|, |z^*|, 1)\}$ against the reference objective $z^*$, rounded to six decimals, 1 when the two have opposite signs, and 2 before the first incumbent. $P$ lies in $[0, 2]$; lower is better. ## Method The heuristics follow their sources, with the departures the Method page lists; new here is the chain: after HiGHS's presolve and before the root LP, each heuristic runs on parallel workers sharing one solution pool, under one budget unit: 1. **FeasibilityJump** (Luteberget and Sartor, 2023): LP-free jump moves on a weighted violation. 2. **FPR** (Salvagnin, Roberti and Fischetti, 2025): fix, propagate, repair. 3. **LocalMIP** (Lin, Zou and Cai, 2024): local search with lift and breakthrough moves. 4. **Scylla** (Mexi et al., 2023): fix-propagate-and-project around a PDLP pump; off by default. 5. **Ruin-and-repair** and **recombination** (after NVIDIA cuOpt): from the pool's best point and from pairs of pool points; off by default. A heuristic's budget is its effort times `nnz << 10`, vanilla HiGHS's own FeasibilityJump limit, and it runs only if its effort is above zero. The defaults run FJ, FPR and LocalMIP; their efforts and patiences were tuned on 90 instances and confirmed on the other 143. Details, pseudocode and the other features: [Method](docs/method.md). ## Results The paired primal integral of the patched HiGHS over vanilla HiGHS on `mipfeas` (below 1: the heuristics ahead): | Instances | n | Primal-integral ratio | 95% CI | Better / tied / worse | |---|---|---|---|---| | All | 233 | 0.763 | [0.684, 0.852] | 114 / 24 / 95 | | Held-out | 143 | 0.871 | [0.782, 0.970] | 63 / 19 / 61 | Setup: the 233 MIPLIB 2017 instances of `mipfeas`, 600 s, one seed, 16 workers on an AMD Ryzen 9 3950X (16 cores), release v0.1.0 on HiGHS v1.15.1 against unpatched HiGHS v1.15.1 at default options; held-out instances were not used for tuning ([Results](docs/results.md) also gives the 95 never seen before the final run). The heuristics reach a good solution sooner; at the time limit the patched solver is slightly ahead. From v0.1.10 on, releases run on HiGHS v1.16.0. [Results](docs/results.md) has the full table and how to reproduce it. ## Usage ```bash pip install git+https://github.com/spoorendonk/mip-heuristics # the Python package; compiles the patched HiGHS ``` In a clone, with `./build/bin/highs` built as in the [quick reference](docs/quickref.md). The patch's options are HiGHS options, set in an options file: ```console $ printf 'mip_heuristic_fj_effort = 0\nmip_heuristic_local_mip_effort = 0\n' > run.opts $ ./build/bin/highs --options_file run.opts model.mps Running HiGHS 1.16.0 (git hash: …): Copyright (c) 2026 under MIT licence terms Includes third-party software components, see THIRD_PARTY_NOTICES.md for full details mip-heuristics patch active (custom MIP presolve heuristics; spoorendonk/mip-heuristics) ``` ```python from mip_heuristics import Highs # HiGHS's highspy, built on the patched HiGHS h = Highs() h.setOptionValue("mip_heuristic_fj_effort", 0.0) # FJ off, the rest at the defaults h.readModel("model.mps") h.run() print(h.getModelStatus(), h.getInfo().objective_function_value) ``` More: [Quick reference](docs/quickref.md) · [Options](docs/options.md) · [Results](docs/results.md) · [Method](docs/method.md) · [C++ reference](docs/cpp.md). ## Citing Cite the paper for the results and the archived release for the code. GitHub's *Cite this repository* reads [`CITATION.cff`](https://github.com/spoorendonk/mip-heuristics/blob/main/CITATION.cff). ```bibtex @misc{spoorendonk2026presolveheuristics, title = {Presolve heuristics in {HiGHS}: implementation and computational study}, author = {Spoorendonk, Simon}, year = {2026}, eprint = {2609.22938}, archivePrefix = {arXiv}, primaryClass = {math.OC}, url = {https://arxiv.org/abs/2609.22938} } ``` ```bibtex @software{spoorendonk2026mipheuristics, title = {mip-heuristics}, author = {Spoorendonk, Simon}, year = {2026}, publisher = {Zenodo}, doi = {10.5281/zenodo.22837481}, url = {https://doi.org/10.5281/zenodo.22837481} } ``` The heuristics are their authors' work: cite the paper of the one you use ([References](docs/method.md#references)). The `mipfeas` benchmark and its metric are Bussieck and Dirkse's ([*Expanding the Focus*](https://www.gams.com/blog/2026/03/expanding-the-focus-introducing-the-mipfeas-benchmark/), GAMS, 2026). ## License MIT. See [LICENSE](https://github.com/spoorendonk/mip-heuristics/blob/main/LICENSE). fj.h ==== .. code-block:: c #pragma once #include "heuristic_context.h" #include #include #include class SolutionSink; namespace fj { // Patience: `mip_heuristic_fj_patience`, a multiple of `nnz << 10` — the // same unit as this heuristic's effort option (issue #111, made an option // by #106, put on the effort unit by #116). FJ's counter is in step // units, so its value is not comparable with the other three heuristics' // — do not read equal numbers as equal tolerances. // // Scope: **per worker**, matching `mip_heuristic_fj_effort`, which sizes // one worker's allowance rather than a whole dispatch // (`budget_is_per_worker` in mode_dispatch's `kChain`). The // runner-level gate is therefore `num_workers` times this, and the // worker-level gate is the value itself. FJ is the only entry with that // scope; the others size a whole dispatch and are divided across // the pool. // // The default is 0, which disables the gate entirely (#107). `nnz << 8` // (0.25), a quarter of FJ's per-worker budget unit, is what FJ used // before and the model the other three were moved onto. The // worker-level gate reads FJ's own `effortSinceLastImprovement`, not // effort since the incumbent moved (#191; see fj_worker.cpp). The default is registered in // `third_party/highs_patch/apply_patch.cmake` and pinned by // `tests/test_smoke.cpp`; `dev/options.md` carries the calibration // notes. // Runs N continuous `parallel::for_each` FjWorkers with per-worker // self-termination, each seeded differently; a worker that finishes is // rebuilt in place with a fresh seed. Set `threads=1` for a single // worker whose behaviour is reproducible under a fixed `random_seed`. // // Implements the uniform runner contract; see heuristic_context.h. DispatchOutcome run(const ProblemView& problem, const HeuristicBudget& budget, ExecutionContext& exec, SolutionSink& sink); // One FjWorker slot on the calling thread until `exec` says stop (#171), // rebuilt whenever it stalls, from `source` first. The rebuilt worker // starts from that point unperturbed. See `run_until_stopped` in // heuristic_context.h for the contract. [[nodiscard]] size_t run_until_stopped(const ProblemView& problem, const HeuristicBudget& budget, const ExecutionContext& exec, int worker, const RestartSource& source, SolutionSink& sink); // A slot keeps its `FjWorker`, and so FJ's model, across rebuilds and // resets it (#323). Test hook: `true` builds a new worker per rebuild // instead, as before #323, so a test can check that a reset slot searches // as a rebuilt one. Process-global; set it only with no dispatch running. void set_fresh_rebuilds_for_test(bool fresh); // A worker's start as `build_worker` hands it over: its slot, whether it is // a rebuild, whether it exchanges, and the point (empty: the bound start). struct WorkerStartForTest { int slot = -1; bool rebuild = false; bool exchange = false; std::span start; // The column upper bounds the worker searches: its slot's propagated // ones (#386), else the model's. std::span upper; }; // Test hook (#365): called with every worker start, from the worker's // thread, so `observer` must be thread-safe; empty turns it off. // Process-global; set it only with no dispatch running. void set_start_observer_for_test(std::function observer); } // namespace fj heuristic_context.h =================== .. code-block:: c #pragma once #include "deadline.h" #include "heuristic_common.h" #include "lp_data/HConst.h" #include "lp_data/HighsLp.h" #include "util/HighsInt.h" #include #include #include #include #include #include #include #include #include #include struct HighsLogOptions; class LeastViolatedPoint; class SharedFjWeights; class SolutionSink; // Common execution scaffold for the four presolve heuristics (issue #94). // // Before this header, each of FJ / FPR / LocalMIP / Scylla re-derived the // same ~10-line block of constants for itself (`ParallelSetup`: csc, // num_workers, base_seed, worker_budget, default_run_cap, stale_budget), // and the model sizes on top of that. The three structs below carve that // single struct along its actual seams — what the heuristic *searches*, // what it may *spend*, and how it *runs* — so a heuristic's entry point can // take exactly the parts it needs, and `mode_dispatch` can build the // expensive part (the CSC transpose) once for the whole chain. // // `fpr_lp.cpp` takes `make_exec` / `make_budget` and builds its view with // `problem_view` over the CSC its setup built: it runs on the same // continuous parallel runner but keeps its own `LpFprSetup` for the LP // references, reduced costs and shared `ContestedPdlp` that the presolve // heuristics have no equivalent of. // // Ownership: solution submission is not here — it lives in `SolutionSink` // (solution_sink.h), which inside HiGHS is the `IncumbentSink` that // `mode_dispatch::run_sequential` owns and threads through each heuristic's // entry point. Per-worker effort/staleness bookkeeping lives in // `WorkerBudgetState` (worker_base.h); `HeuristicBudget` holds the // *derived* values each worker's base struct receives on construction. // Every chain heuristic's budget comes from their own // `mip_heuristic__effort` option; FJ's sizes `per_worker` and lets // `total` scale with the pool, the others size `total` and are // divided across it (see mode_dispatch.cpp). // The uniform runner contract every presolve heuristic implements: // // DispatchOutcome ::run(const ProblemView &problem, const HeuristicBudget &budget, // ExecutionContext &exec, SolutionSink &sink); // // `mode_dispatch::run_sequential` owns all four arguments — including the // source tag the sink attributes this heuristic's solutions with — and books // the returned outcome through `EffortLedger`, the single point of effort // accounting. No heuristic self-books. The per-heuristic headers describe // only what their own runner does differently. // // `ExecutionContext` is passed by non-const reference to match the entry // signature, but it is immutable for the duration of a dispatch: it is // shared by every worker of every heuristic in the chain, so caching // mutable per-dispatch state on it would be an unsynchronised shared // write. Its methods are `const`. // Why a dispatch stopped (#303), recorded at the point that stopped it // rather than inferred from its effort afterwards. Inference was the // deadline tests' only option, and it took a second, longer run of the same // configuration to say "the clock did this" — a two-sided comparison that // load from outside ctest could break. The reason is a one-sided fact about // one run. // // The runner (`ContinuousLoopState::request_stop`) keeps the *first* reason // that set its stop flag: once the flag is up every other worker leaves on // it, so later reasons are consequences, not causes. enum class StopReason : uint8_t { // Nothing stopped it: every worker slot retired on its own (an attempt // that charged nothing), or the dispatch declined to run at all. kDone, // `past_deadline()`: the solve's wall clock, or a caller's stop flag // where one is attached (the HiGHS dispatch attaches none). Also a // setup bail (`DispatchOutcome::abandoned`), which is the same clock. kDeadline, // `terminated()` with the clock not yet past: the solver's terminator. kInterrupt, // The dispatch's effort budget is spent. kBudget, // The dispatch-level staleness gate, the heuristic's patience. kPatience, }; // The `[Heur] stopped_by=` spelling. constexpr const char* stop_reason_name(StopReason reason) { switch (reason) { case StopReason::kDone: return "done"; case StopReason::kDeadline: return "deadline"; case StopReason::kInterrupt: return "interrupt"; case StopReason::kBudget: return "budget"; case StopReason::kPatience: return "patience"; } return "done"; } // What one dispatch of a heuristic did, as its runner reports it (issue // #119). Used to be a bare `size_t` effort count. // // The second field exists because zero effort has two causes that a log // cannot tell apart. A heuristic that searched and produced nothing and // one that never searched at all — because #117 made the *sequential* // setup abandon its work on an already-passed deadline — both booked // `effort=0 found=0`, and the #113 calibration bins the second as // "barren", which is the population its patience estimate rests on. A // setup bail is not a barren dispatch: it is a cost of setup, and it // happens precisely on the large, hard instances the calibration is most // sensitive to. // // Why the *return type* rather than a narrower channel. The flag has to // travel from a bail site deep inside one heuristic to `run_sequential`, // which is the only caller and the only booker. The two alternatives were // a mutable field on `ExecutionContext` — narrower in signatures, but that // object is shared by every worker of every heuristic in the chain and is // documented immutable for exactly that reason, and it would need a reset // per heuristic that nothing forces anyone to write — and a flag on // `IncumbentSink`, which is the per-heuristic mutable channel // `run_and_charge` already reads across the call but has nothing to do // with solution submission. Both smuggle per-dispatch state into an // object that outlives the dispatch; a return value cannot leak into the // next heuristic because there is no state to forget to clear. // // `[[nodiscard]]`, for the reason `SolutionSink::offer` is: a dropped // outcome loses both the effort — which `run_sequential` books into // `heuristic_effort_used` and nothing else can recover — and the bail flag // this issue exists to carry. `-Werror=unused-result` on our library and // test targets is what makes the attribute a build failure // rather than a warning that scrolls past. It costs a caller that wants // one field nothing: `run(...).effort` is a *use* of the return value, so // only a call whose whole result is thrown away trips it, and the single // such caller (a test driving warm-start counters) spells the discard. struct [[nodiscard]] DispatchOutcome { // Effort charged, in this heuristic's own unit. `run_sequential` // books exactly this into `heuristic_effort_used`. size_t effort = 0; // What ended the dispatch; see `StopReason`. StopReason stopped_by = StopReason::kDone; // This dispatch abandoned its sequential setup on the wall-clock // deadline and never searched (issue #117's bail, made visible). It // implies `effort == 0`, but the converse is what this field exists to // deny. // // Scope: *only* the deadline bails in `fpr::precompute_var_orders` and // `scylla::precompute_config_var_orders` set it, plus the dive-time // equivalent. A heuristic declining for another reason — a degenerate // model, a zero budget, a `ContestedPdlp` that failed to initialise — // reports a plain zero, because none of those is a dispatch the clock // cut short. bool abandoned_setup = false; // The bail, spelled once so the two sites cannot disagree. static DispatchOutcome abandoned() { return {.effort = 0, .stopped_by = StopReason::kDeadline, .abandoned_setup = true}; } }; // Read-only view of the model a heuristic searches: everything a worker // reads, and nothing of the solver it was read from (issue #170). Every // member but the two snapshots is a non-owning pointer, a derived size or // a tolerance; the pointees are owned by whoever built the view — the // solver and `run_sequential`'s CSC local for the presolve chain // (`make_problem(HighsMipSolver&, CscMatrix&)`), or a `ProblemStorage` for // a caller that owns its model — and outlive every worker reading them. // Built once per dispatch and passed by const reference — the snapshots // make it no longer trivially cheap to copy. struct ProblemView { // The column-wise matrix, which FJ builds its own row-wise copy from. // Never read its bounds, cost, offset, sense or integrality: the fields // below replace them. const HighsLp* model = nullptr; // Column and row bounds as the workers enforce them. The HiGHS adapter // points these at the presolved model's own; the core `make_problem` // maps a magnitude at or above HiGHS's `infinite_bound` to infinity, as // HiGHS's own model assessment does, and rounds an integer column's // inward (`ceil(lb - feastol)`, `floor(ub + feastol)`), as the presolved // model's already are. const std::vector* col_lower = nullptr; const std::vector* col_upper = nullptr; const std::vector* row_lower = nullptr; const std::vector* row_upper = nullptr; // The objective in *minimisation* form, and the integrality of every // column (#170). Every worker reads these, so the heuristics only ever // see a minimisation problem — as they do inside HiGHS, whose presolve // turns a maximisation model into one before any heuristic runs. Every // objective a worker computes, and so every objective a `SolutionSink` // or `SolutionPool` holds, is `offset + col_cost . x` in this form: the // negated original objective for a maximisation model. const std::vector* col_cost = nullptr; double offset = 0.0; const std::vector* integrality = nullptr; // Row-wise copy of `model->a_matrix_`. const std::vector* ar_start = nullptr; const std::vector* ar_index = nullptr; const std::vector* ar_value = nullptr; const CscMatrix* csc = nullptr; // Per-column up- and down-lock counts, for FPR's trivially-roundable // fixings. const std::vector* uplocks = nullptr; const std::vector* downlocks = nullptr; // `mip_feasibility_tolerance` and `small_matrix_value`, as // `HighsMipSolverData::feastol` / `epsilon` hold them. double feastol = 0.0; double epsilon = 0.0; // Derived sizes, previously recomputed at every call site that wanted // one of them. HighsInt ncol = 0; HighsInt nrow = 0; size_t nnz = 0; // Snapshot of `HighsMipSolverData::incumbent`, copied once per dispatch // on the dispatching thread (issue #98). Workers read *this*, never // `mipdata->incumbent`: submission is immediate, so a peer worker's // accepted solution runs `addIncumbent`, whose whole-vector assignment // (`incumbent = sol;`) rewrites the live buffer under a concurrent // reader — element-wise while the sizes match, reallocating out from // under it on the empty-to-sized transition. Empty when the solver had // no incumbent at dispatch time. `fpr_lp` takes the same snapshot, through // `problem_view`. // // The snapshot is the *floor* a worker starts from, not necessarily what // it gets: both readers consult the shared pool first, which holds the // seeded incumbent plus everything accepted since (`IncumbentSink` seeds // it at construction and every accept goes through it, under its own // lock). So dropping the live read costs neither of them a warm start — // LocalMIP's `resolve_worker_start` only reaches this copy with an empty // pool, i.e. when nothing has been submitted and the live incumbent // still equals it, and `fj.cpp` resolves pool-first for the same reason. // Nothing may read this *instead* of the pool: an `FjWorker` rebuilt // mid-dispatch would then silently lose a peer's find. std::vector incumbent; // Per-column snapshot of `HighsDomain::isBinary`, taken with the // incumbent and for the same reason (issue #99). `addIncumbent` runs // `getDomain().propagate()` and `redcostfixing.propagateRootRedcost`, // both of which tighten the root domain's bound vectors element-wise, // while workers classify columns from those same vectors. Unlike the // incumbent this can never dangle — the bound vectors are sized once at // setup — so it is a torn read rather than a use-after-free, but it is // still a race, and a column's classification flipping mid-dispatch is // not something any worker is written to expect. // // Scope: taken once for the *whole* FJ -> FPR -> LocalMIP -> Scylla // chain, so a column that root propagation fixes after FJ's first // incumbent is still classified with its pre-FJ value by the other // three. Deliberate, and cheap: workers enforce the view's // `col_lower`/`col_upper`, never `HighsDomain`'s, so the classification // was already decoupled from the bounds they respect. // // `uint8_t` rather than `std::vector`: workers index this from // hot loops, and the bit-packed specialisation costs a shift and mask // per read plus a proxy object. Concurrent *reads* of a frozen // `vector` would be well-defined — the hazard is concurrent // read/write of neighbouring bits, which cannot arise for a mask built // before the parallel region — so this is a throughput choice, not a // correctness one. std::vector binary; // A model with no columns or no rows: every heuristic declines it. [[nodiscard]] bool degenerate() const { return ncol == 0 || nrow == 0; } // `x`'s objective in the view's minimisation form, offset included. [[nodiscard]] double objective(const std::vector& x) const { double obj = offset; for (HighsInt j = 0; j < ncol; ++j) { obj += (*col_cost)[j] * x[j]; } return obj; } }; // What a `ProblemView` points at when there is no `HighsMipSolverData` to // borrow it from — a caller running the heuristics on a model it owns, // such as the original model read with `Highs::readModel`. Must outlive // every view built over it. struct ProblemStorage { std::vector ar_start; std::vector ar_index; std::vector ar_value; std::vector uplocks; std::vector downlocks; CscMatrix csc; // The negated costs of a maximisation model; empty otherwise. std::vector col_cost; // The bounds, huge ones mapped to infinity and integer columns' rounded // inward. std::vector col_lower; std::vector col_upper; std::vector row_lower; std::vector row_upper; // All-continuous for a model with no `integrality_` (a pure LP); empty // otherwise. std::vector integrality; }; // Why `make_problem` refused a model. The kinds are distinct because the // caller acts on them differently: a malformed model is a bug in whoever // built it, an infeasible one is an answer about the model, and an // unsupported one needs another tool. The line between the first two is // HiGHS's own (`assessLp`, `assessBounds`, `assessMatrix`): what it refuses // with an error is malformed, what it lets through with a warning or // solves to infeasibility is infeasible. struct ProblemError { enum class Kind { // Structurally broken: sizes that disagree with the dimensions, a // matrix that is not column-wise with them, starts that do not begin // at 0 or are not monotone, row indices out of range or repeated // within a column, an integrality or sense outside its enum, a NaN // anywhere, a non-finite (or `infinite_cost`-sized) cost or offset, // a coefficient at or above `large_matrix_value`, or a lower bound // at `+infinite_bound` or an upper one at `-infinite_bound`. kMalformed, // Provably infeasible on its face: crossed bounds (an integer column's // after rounding inward), or an empty row whose bounds exclude 0. kInfeasible, // A semi-continuous or semi-integer column, which the workers do // not model: they read integrality as "anything but continuous is an // integer", which would drop the column's zero branch. kUnsupported, }; Kind kind; std::string message; }; // A view over a caller's own `model`, with `storage` filled the way // `HighsMipSolverData::runSetup()` fills the solver's copies: the row-wise // matrix through `highsSparseTranspose`, the lock counts by the same rule, // and the CSC from the row-wise matrix as `make_problem` builds it. The // binary mask is `HighsDomain::isBinary` at the normalised bounds (an // integer column with bounds exactly `[0, 1]`), and there is no incumbent. // `feastol` / `epsilon` are the caller's `mip_feasibility_tolerance` / // `small_matrix_value`. `model` must outlive the view. // // Normalised as HiGHS's presolve normalises a model before its heuristics // see it, so that nothing a worker reports can violate what it was given: // minimisation form (a maximisation model's costs and offset negated into // `storage`), bounds of magnitude `infinite_bound` or more mapped to // infinity, integer column bounds rounded inward, and a model without // `integrality_` all continuous. Everything is checked in one linear pass // over the model; see `ProblemError` for what is refused. std::expected make_problem(const HighsLp& model, ProblemStorage& storage, double feastol, double epsilon); // What a rebuilt FJ or LocalMIP worker restarts from (#200); a slot's first // worker is not a restart and ignores it. `kDefault` is the restart before // the option: LocalMIP a pool draw (`RestartPolicy::kMixed`) perturbed, FJ // the pool's best. `kBest` is the best point unperturbed — Local-MIP v2's // default `restart = best` and CP-SAT ViolationLS's restart — which for FJ // is `kDefault` exactly. `kHybrid` is Local-MIP v2's `hybrid_restart` on // the same point (`hybrid_restart`). See `rebuild_restart_point`. enum class RestartPoint : uint8_t { kDefault, kBest, kHybrid }; // Some column has a cost above the matrix's `epsilon` in magnitude. Without // one every feasible point has the same objective, so there is nothing to // improve. O(ncol); called once per dispatch on the dispatching thread. [[nodiscard]] inline bool has_objective(const ProblemView& problem) { return std::ranges::any_of(*problem.col_cost, [&](double c) { return std::abs(c) > problem.epsilon; }); } // One heuristic's slice of the presolve effort envelope. `total` used to // travel separately as a bare `max_effort` parameter while the other three // were fields of `ParallelSetup`; they are one thing and now travel as one. struct HeuristicBudget { size_t total = 0; // whole-dispatch ceiling, summed over workers size_t per_worker = 0; // total / N (floor division) size_t attempt_cap = 0; // per-attempt cap: max(total / (N * 10), 1) // Runner-level staleness ceiling: the dispatch stops once // `ContinuousLoopState::effort_since_improvement` — summed over every // worker — crosses this. Absolute and instance-scaled since issue // #111 (`patience_threshold(nnz, , // total)`, sized by the caller from `mip_heuristic__patience`), // not the `total / 4` it used to be. A quarter of the budget is not a // patience criterion: it says "I have spent a quarter of what I was // given", which is true at every budget and therefore bounds nothing. // A quarter of the budget is what the *clamp* is (#116), which is a // different job — see `kPatienceCeilingDivisor`. size_t stale = 0; // Per-worker share of the same ceiling. The runner's counter // aggregates N workers, so one worker's share is `stale / N`; that // relation is not new, it is what `total / 4` per worker against // `total / 4` per dispatch already meant, and what FJ's `nnz << 8` // against a `N * nnz << 8` runner gate already was at the shipped // default. Scylla is the documented exception — see scylla_worker.cpp. size_t worker_stale = 0; // FJ in `run_until_stopped` only, default off (#191). When set, a // worker that retires — FJ's own `effortSinceLastImprovement` crossing // `worker_stale`, or `per_worker` spent — ends the run instead of being // rebuilt: SCIP's feasjump, one run ended by effort without progress on // violations or objective. The stall is read at FJ's callback, so it // is seen no sooner than 500000 effort units in, whatever `worker_stale` // says (#194; HiGHS's own FJ has the same floor). bool fj_stall_ends_run = false; // LocalMIP's counterpart (#203), default off; the presolve dispatch // never sets it. (`local_mip::run` would apply its counter but never // end a run on it.) When set, a worker's patience counter — effort since // the sink's best moved — also restarts whenever its violated-row count // falls to at most 90% of the count at the counter's last restart, and a // worker that retires (that counter crossing `worker_stale`, `per_worker` // spent, or its feasible random walks used up) ends the // `run_until_stopped` run instead of being rebuilt: SCIP's localsearch, // one run ended by effort without cutting violations by 10% or improving // the objective. bool local_mip_stall_ends_run = false; // FJ and LocalMIP: the point a rebuilt worker restarts from (#200). RestartPoint restart = RestartPoint::kDefault; // LocalMIP only, default off (#200): a rebuilt worker's weights start, // with probability one half, at draws from {1, 2} instead of 1 — CP-SAT's // restart weight draw, on LocalMIP's integer weights. bool randomize_restart_weights = false; // FJ only, off in a budget built by hand, though the solver option is on // by default (#206, #365, #312): each slot is cuOpt's lane // `slot % 16`, and its first worker starts as that lane does // (`lane_persona`, `apply_lane_start`), in the chain and in a // long-lived slot alike. bool fj_personas = false; // FJ only, off in a budget built by hand, though the solver option is on // by default (#218, #312): the slots on cuOpt's exchange lanes // (`is_exchange_slot`) search with its cardinality exchange over the // model's exact-k rows, in the chain and in a long-lived slot alike. bool fj_exchange = false; // This heuristic was handed nothing, and must therefore do nothing // (issue #106). // // `mip_heuristic__effort = 0` sizes `total` to zero, and #107 // spells "this heuristic is excluded from the configuration" exactly // that way — a zero-pattern of four continuous parameters rather than a // separate discrete subset dimension, which is what keeps its search // tractable. That reduction needs a zero budget to be worth exactly // what omitting the heuristic is worth, so every entry point checks // this alongside `ProblemView::degenerate()` and returns before any // setup. // // Since #167 the zero *is* the omission — `mip_heuristic_suite` is // gone and the effort option is the only selector — so what this // guarantees is no longer an equivalence between two spellings but the // meaning of the one that is left. The history is worth keeping // because it is what the guarantee costs: `fpr_lp` draws from // upstream's `mip_heuristic_effort` envelope and never reads a presolve // option, so until #164 gave it an option of its own, zeroing `fpr` // left the dive-time heuristic running. // `run_opportunistic_loop` already declined a zero total, // but three of the four heuristics do real work before they reach it — // Scylla builds a `ContestedPdlp` (a whole `Highs` LP copy), the // per-config variable orders and N workers; FPR precomputes its // variable orders — and that work is neither free nor charged, so it // was invisible in the effort total while still costing wall time. [[nodiscard]] bool disabled() const { return total == 0; } }; // How a heuristic runs: the worker count, the RNG base seed, the deadline, // the log, and the one termination predicate. Nothing in it names the // solver (#170): the HiGHS adapter builds one with `make_exec` // (highs_context.h), and a caller running the workers on its own threads // builds its own. // // Historical note on `attempt_cap`: the deleted epoch-gated runner gave FJ a // separate cadence (`kEpochsPerWorkerFj = 20` against 10 for the rest), on // the grounds that "FJ's synchronization cadence matters for pool-crossover // behaviour and a change could regress on FJ-dominant instances". That only // ever applied to the epoch runner — the continuous runner has always used // this cap for FJ too — so #92 removed a constant, not a behaviour. The // concern was never benchmarked; recorded here so it is not lost with the // constant, but no cadence changed for any surviving execution path. struct ExecutionContext { size_t num_workers; // highs::parallel::num_threads(), at least 1 uint32_t base_seed; // seeded from `random_seed` via heuristic_base_seed // The run's wall-clock deadline, and the only half of "should we // stop?" a worker thread may poll (issue #114). Also handed as it is // to the layers below a heuristic's runner: `fpr_core`'s DFS and the // repair search under it have no `ExecutionContext` (issue #117), and // taking this one rather than building their own is what keeps them // from stopping against a different clock or limit than their runner. // // `HighsTimer::read()` is `const` and, for the solve clock, writes // nothing — it reads `clock_start`/`clock_time` and calls // `getWallTime()`. Nothing starts or stops that clock while a // heuristic dispatch is in flight, so concurrent readers are safe. // That is what separates this from `terminated()` below, and it is why // every presolve heuristic can poll the deadline from inside its own // inner loop without a poller seat. // // In the HiGHS adapter it is the solver's own clock rather than a // `steady_clock` snapshot (`make_exec`): a second origin would no longer // agree with the `[Heur] start_s`/`end_s` the ledger emits, which the // tests and `bench/parse_highs_log.py` both read against this same // limit. `HighsTimer` bottoms out in `high_resolution_clock` and is // therefore not monotonic (see `effort_ledger.h`); that risk is // pre-existing and is the price of one shared origin. Deadline deadline; // Where the workers' own solvers log (FJ's `FeasibilityJumpSolver`). // Held by reference, so it must outlive the context, and it must be a // working one: a default-constructed `HighsLogOptions` holds null // `output_flag` / `log_to_console` / `log_dev_level` pointers, which the // logger dereferences. `Highs::getOptions().log_options` is one; a // caller without a `Highs` points those three at its own values. const HighsLogOptions& log_options; // The external half of "should we stop?", or empty when nothing // outside the clock can end the run. In the HiGHS adapter it is // `HighsMipSolverData::terminatorTerminated()`, which *writes* // `mipsolver.termination_status_` when a terminator is attached — so // it is called only through `terminated()`, and only by one caller at // a time. std::function terminator; // A caller's own stop flag, or null (#171). The HiGHS adapter leaves // it null; a caller driving a worker with `run_until_stopped` points it // at the flag it sets to end the run. It is read, never written, so it // joins the clock on the write-free side of the split above: any worker // thread may poll it, and it is polled wherever the deadline is — inside // an attempt as well as between attempts, which is what bounds a stop's // latency by a worker's poll cadence rather than by one attempt's budget. // A sub-algorithm given a `Deadline` sees it only when the caller also // puts it on `deadline.stop`, as a long-lived slot does (#356); without // that, recombine's bound-prop arm waits out its recombination. const std::atomic* stop = nullptr; // Where LocalMIP's workers retain their least-violated infeasible point // (#188), or null to retain nothing. Caller-owned and thread-safe; see // least_violated.h. The HiGHS adapter leaves it null, and FJ, FPR and // Scylla never read it. LeastViolatedPoint* least_violated = nullptr; // A caller's early-restart trigger for a `run_until_stopped` slot // (#189), or empty for none. Asked on the slot's thread before every // attempt; true rebuilds the worker at once, from the caller's // `RestartSource` first, as a stall would. It lets a worker take up a // peer's much better solution without waiting for its own patience to // run out — ReXi's "Improve"; the margin is the caller's to choose, // since only the caller knows both its pool's best and this worker's. // It names no slot, so a per-worker rule needs one `exec` per slot; a // shared one calls it from every slot's thread. The presolve dispatch // never reads it. std::function restart_now; // The GPU climber's latest weights, which every FJ worker `fj::run` and // `fj::run_until_stopped` build or reset starts from (#376), or null. // Thread-safe. The HiGHS adapter sets it, in a GPU tree with the // long-lived race requested, on the presolve chain's context and on // each long-lived slot's; no other heuristic reads it. const SharedFjWeights* fj_start_weights = nullptr; // The write-free half of "should we stop?": the caller's stop flag or // the wall-clock deadline. Any worker thread may call it. [[nodiscard]] bool past_deadline() const { return (stop != nullptr && stop->load(std::memory_order_relaxed)) || deadline.expired(); } // The full "should we stop?" predicate. Three hand-rolled copies of // it existed before this struct. // // Not thread-safe for concurrent callers: `terminator` may write (see // above). That write — not the clock read — is the whole reason this // one needs a single caller. `mode_dispatch` calls it between // heuristics, with every parallel region already joined, and inside a // parallel region the worker holding `ContinuousLoopState`'s claimable // poller seat calls it on everyone's behalf. // // There is no longer an exception: FPR's multi-attempt inner loop used // to poll this directly from its own worker thread, which was a race // whenever a terminator was attached. It polls `past_deadline()` // instead (issue #114), which is the half it actually needed, so the // seat is now the only route to the terminator. [[nodiscard]] bool terminated() const { return (terminator && terminator()) || past_deadline(); } // Deterministic seed for worker `w`. The runner seeds its own per-worker // `Rng` with this, and heuristics that pre-construct their workers seed // them with it too — three hand-written copies of the expression before // it lived here, which is three chances for one of them to drift. [[nodiscard]] uint32_t worker_seed(int w) const { return base_seed + (static_cast(w) * kSeedStride); } }; // Split a heuristic's slice of the effort envelope into the per-worker, // per-attempt and staleness ceilings its workers and the runner use. // // `stale` is passed in rather than derived here (issue #111): it is the // one quantity in this struct that must *not* be a function of `total`, // and every caller knows the model's `nnz` and its heuristic's // patience value. See `patience_threshold` in heuristic_common.h. inline HeuristicBudget make_budget(size_t total, size_t num_workers, size_t stale) { // A zero total is "this heuristic is excluded" (issue #106), so every // derived ceiling is zero too and `disabled()` holds. Spelling it out // rather than letting the expressions below run: `attempt_cap` floors // at 1, so a zero budget used to license one attempt — the whole of // Scylla's, which charges a full PDLP solve and does not stop for // `attempt_cap` once started — and `stale` arrives here *unclamped*, // because `patience_threshold` special-cases a zero budget by skipping // the clamp. Both are ceilings that only make sense above a budget // that exists. if (total == 0) { return HeuristicBudget{}; } // Designated initialisers for the same reason `make_problem` below // gives them: this aggregate is five `size_t` members in a row, so a // mis-ordered addition converts silently between them. #111 appended // the fifth. return HeuristicBudget{.total = total, .per_worker = total / num_workers, .attempt_cap = std::max(total / (num_workers * 10), 1), .stale = stale, .worker_stale = std::max(stale / num_workers, 1)}; } // The second runner contract (#171). FJ, LocalMIP, ruin and recombine also // expose // // size_t ::run_until_stopped(const ProblemView &problem, const HeuristicBudget &budget, // const ExecutionContext &exec, int worker, // const RestartSource &source, SolutionSink &sink); // // which runs worker slot `worker` on the calling thread — a thread the // caller owns, not the HiGHS task scheduler — until `exec` says stop. It // is the same slot loop the presolve dispatch runs N of in parallel // (`run_on_caller_thread` in opportunistic_runner.h), with two differences: // a stalled worker is always rebuilt rather than retiring its slot // (`attempt_with_rebuild`), and a rebuild asks `source` for its start point // before the sink's own pool. The in-HiGHS dispatch does not use it. // Scylla's (#411) takes a `scylla::Setup` built on the solving thread in // front of these arguments, so it fits no `UntilStopped`; its exceptions to // what follows are in scylla.h. // // What ends it: // - `exec.stop` or the deadline, both polled through `past_deadline()` // inside an attempt on the worker's own cadence (FJ at every upstream // callback, i.e. every 500000 FJ effort units or found solution; // LocalMIP every `kTermCheckWork` counted units or steps) and again // before every attempt; // - `exec.terminator`, before every other attempt; // - `budget.total`, and a `budget.attempt_cap` of 0, which returns before // the first attempt; // - `budget.stale`, the run-level patience; // - a worker that charges nothing even when freshly rebuilt, which // retires the slot: a degenerate view (returned at once, as 0), or FJ // built with `HIGHSINT64`, which never searches. Ruin also returns 0 // at once under `HIGHSINT64`, or with no cost or no non-fixed integer // column; it reads no `restart_now`. Recombine returns 0 at once without // an objective or a non-fixed integer column, reads no `restart_now` and // has no worker to rebuild, so it reads no `worker_stale`. // - for FJ under `budget.fj_stall_ends_run`, the worker retiring: its // `effortSinceLastImprovement` crossing `budget.worker_stale`, or its // spending `budget.per_worker`, ends the run instead of a rebuild, // except a substituted slot's worker whose rejected lift drops the // slot's reduction (#387), which is rebuilt in the slot's own model; // - for LocalMIP under `budget.local_mip_stall_ends_run`, likewise its // worker retiring, with its patience counter also restarted by every // 10% cut in its violated rows. // `make_until_stopped_budget` lifts `total` and `stale`. So a stop is seen // within one poll interval, except while a worker is being built: FJ's // solver construction, FJ's lane plan (`fj_personas`/`fj_exchange`: one // O(nnz) structure pass, the deadline polled once ahead of it) and // LocalMIP's cold-start construction sweep (one O(nnz) pass) poll nothing, // as in the presolve dispatch, and Scylla's PDLP solve in flight and, unless // the flag is on `exec.deadline.stop` too, its FPR rounding (scylla.h). // The other exception is recombine's bound-prop arm: it takes a `Deadline`, which sees // the flag only when the caller puts it on `exec.deadline.stop` as well. // Without that a stop waits out the recombination in progress, and // `attempt_cap`, at most `kRewardNominalEffort`, caps only its DFS, not its // propagation or leaf repair, so that wait is no hard bound. A worker is // rebuilt when it stalls (`budget.worker_stale`; for FJ against its own // `effortSinceLastImprovement`, for LocalMIP against effort since the // sink's best moved) or spends `budget.per_worker`, unless a // `*_stall_ends_run` above ends the run instead. // // `exec.num_workers` is not read; `worker` picks the slot's seed // (`exec.worker_seed(worker)`) and its trace identity, for LocalMIP a slot // other than 0 perturbs its first start, and for FJ under `fj_personas` or // `fj_exchange` it picks the slot's lane (`lane_of`): its start persona, // whether its first start drops the source's point, and the exchange — all // as in the presolve dispatch. // Returns the effort charged, cold-start construction included. // // Thread-safety. Everything runs on the calling thread, and the calls into // the caller's code are: // - `source`, when the slot's first worker is built and whenever a // stalled one is rebuilt; for ruin, before every attempt and every // `kWaitForSeedMs` while a slot waits for its first feasible point; for // recombine, before every step and every `kWaitForSeedMs` while a slot // waits for two pool entries; // - `sink`'s `on_accept`, for every offer the sink's pool accepts, on // this thread and outside the pool lock; // - `exec.terminator`, every other attempt (ruin and recombine: also every // `kWaitForSeedMs` while waiting for a point): this thread holds the // poller seat for the whole run; // - `*exec.stop`, a relaxed load, from inside attempts and between them; // - `exec.restart_now`, when set, before every attempt but the one a // retired worker under a `*_stall_ends_run` ends the run at; // - `*exec.least_violated`, when set: a lock-free read every step and an // `offer` at most every deadline poll (LocalMIP only). // Several threads may each run a slot against one `sink`, `source`, `exec` // and stop flag — `SolutionSink` is thread-safe — but then `source`, // `terminator` and `restart_now` are called concurrently and must be // thread-safe too. // // Exceptions. Nothing here throws of its own accord beyond allocation // failure. An exception thrown by `source`, `on_accept` or `terminator` // propagates out of `run_until_stopped` with the basic guarantee: the slot's // worker is destroyed, no lock is held (`on_accept` runs outside the pool // lock), and `sink` stays usable. Uncaught in a `std::thread`'s body, it // calls `std::terminate`, so a caller whose callbacks can throw catches // around the call. // Where a `run_until_stopped` slot takes its start point, ahead of the // sink's own pool (#171): fill `out` with a point in the view's column // space and return true, or return false to fall back to the pool, the // view's incumbent and finally a fresh construction, in that order. A // point that is not `ncol` long, or holds a non-finite value (a NaN or // an infinity, even on a column whose bound is infinite), is treated as a // false. // Any other point is used after rounding its integer columns to the nearest // integer and clamping every column into the view's bounds (`take_restart`), // so an arbitrary point — a crossover, an LP solution — is a legal start: // FJ leaves the columns it never moves as it found them, and would // otherwise report a fractional integer column as part of a solution. FJ // starts from the point as it is; LocalMIP perturbs it as it does any // restart, except for slot 0's first start, which it takes unperturbed. // `rng` is the slot's own generator, there for a source that wants to draw // — `SolutionSink::get_restart` has this signature, so a source can forward // to another sink's pool crossover. Empty means no source; the presolve // dispatch passes an empty one. using RestartSource = std::function& out)>; // A heuristic's `run_until_stopped`, as the contract above spells it: what a // long-lived slot runs (#356). using UntilStopped = size_t (*)(const ProblemView& problem, const HeuristicBudget& budget, const ExecutionContext& exec, int worker, const RestartSource& source, SolutionSink& sink); // `source`'s point into `out`, rounded and clamped into `problem` as the // contract above says, when there is a source and its point is usable; // otherwise false, with `out` empty. [[nodiscard]] bool take_restart(const RestartSource& source, Rng& rng, std::vector& out, const ProblemView& problem); // Local-MIP v2's `hybrid_restart`, in place on `point` (#200; `restart.cpp` // at shaowei-cai-group/Local-MIP 3bd2d61): each column keeps its value or, // on an even coin, takes its `sample_random_value` — uniform over the // column's integers when it is an integer column with both bounds finite, // uniform over its interval when it is continuous with both bounds finite, // and its value otherwise. A finite integer range wider than // `kSafeInt64DoubleRange` counts as unbounded: no `int64_t` draw covers it. void hybrid_restart(std::vector& point, const ProblemView& problem, Rng& rng); // The point a rebuilt worker restarts from under `policy`, into `out` // (#200), or false — with `out` empty and nothing drawn — under // `kDefault`, or when there is no base point: then the caller takes its // `kDefault` path. The base is `source`'s point, else the pool's best // entry (drawing nothing), else `problem.incumbent`; `kHybrid` then applies // `hybrid_restart`. [[nodiscard]] bool rebuild_restart_point(RestartPoint policy, const RestartSource& source, SolutionSink& sink, Rng& rng, std::vector& out, const ProblemView& problem); // The budget for a `run_until_stopped` slot that only the caller's stop // should end: no ceiling on the run or on one worker, no run-level patience, // `attempt_cap` effort between two of the runner's own checks, and a worker // rebuilt once `patience` of its effort has gone by without moving the // sink's best. Both in the heuristic's own effort unit. A `patience` of // 0 means no gate, as it does for every `mip_heuristic__patience` // option: the worker is then rebuilt only if it retires by itself. inline HeuristicBudget make_until_stopped_budget(size_t attempt_cap, size_t patience) { constexpr size_t kUnbounded = std::numeric_limits::max(); return HeuristicBudget{.total = kUnbounded, .per_worker = kUnbounded, .attempt_cap = attempt_cap, .stale = kUnbounded, .worker_stale = patience == 0 ? kUnbounded : patience}; } local_mip.h =========== .. code-block:: c #pragma once #include "heuristic_context.h" #include #include class SolutionSink; namespace local_mip { // Patience: `mip_heuristic_local_mip_patience`, a multiple of // `nnz << 10` — the same unit as this heuristic's effort option (issue // #111, made an option by #106, put on the effort unit by #116). // LocalMIP's counter is in coefficient accesses. // // Scope: **whole dispatch**, matching `mip_heuristic_local_mip_effort`. // Each worker's share is this divided by the worker count // (`HeuristicBudget::worker_stale`); the runner-level gate uses the // value as it stands. // // The default 4096 reproduces the pre-#111 runner gate: at the default // effort 0.1821 that gate was `heuristic_effort_budget(nnz, 0.1821) / 4` // = 3729 x nnz, and 4096 is the neighbouring power of two (1.10x). This // is the heuristic #111's evidence came from — LocalMIP on `fiball` // found its one solution at 0.6 s and then spent 11 s of a 12 s limit // finding nothing else, because the gate it was measured against grew // with the budget. 0 disables the gate entirely. The default is // registered in `third_party/highs_patch/apply_patch.cmake` and pinned // by `tests/test_smoke.cpp`; `dev/options.md` carries the // calibration notes. // Compile-time instrumentation switch (R3-1 round-4 review). Driven // by the `MIP_HEURISTICS_INSTRUMENT` CMake option, which defaults to // ON when tests are being built and OFF otherwise. When false, the // warm-start counter increments below compile out via // `if constexpr (kInstrumented)` in `local_mip.cpp` and the API calls // become no-ops (`reset_*` writes nothing, `warm_start_counters` just // returns zeros). The tests then exercise the counters under their // own translation unit which sees `kInstrumented == true`. Production // release builds can opt out with `-DMIP_HEURISTICS_INSTRUMENT=OFF`. #if defined(MIP_HEURISTICS_INSTRUMENT_ENABLED) && MIP_HEURISTICS_INSTRUMENT_ENABLED inline constexpr bool kInstrumented = true; #else inline constexpr bool kInstrumented = false; #endif // Test-only introspection: counts how many times each branch of // `resolve_worker_start` fired during the current process. The three // branches correspond to the three #75 cold-start fallback rungs: // - `pool` : pool.copy_best succeeded (warm-start from #74 pool). // - `incumbent` : pool was empty, mipdata->incumbent picked up. // - `construction` : pool and incumbent both empty; either the // paper's construction phase ran or its // cold-start cache was reused (a single first- // worker construction can amortise across N // peers via `cold_start_cache`). // Counters cover the `run` start-resolution paths only; restart-callback // warm-starts inside the parallel loops are NOT counted (their work // happens after the initial start has already been resolved). // Call `reset_warm_start_counters()` before a HiGHS run, then read // `warm_start_counters()` after to assert which path actually fired. // Used by R1-8 / R2-7 / R3-3 round-3 review tests to distinguish #74 // (pool warm-start) from #75 (cold-start construction); without this // the integration tests can't tell those paths apart since both // produce non-zero effort. // // When `kInstrumented == false`, all three counters always read zero // regardless of how many runs have completed. struct WarmStartCounters { int64_t pool; int64_t incumbent; int64_t construction; }; void reset_warm_start_counters(); WarmStartCounters warm_start_counters(); // Test-only introspection on the search loop's wall-clock poll (#162). // `polls` counts how many times `LocalMipWorker::run_attempt` asked // `ExecutionContext::past_deadline()`; `effort` is the effort those // attempts charged. `max_gap` is the most effort any attempt charged // between two polls, or between its last poll and its end, and // `max_iteration` the most any one pass of its loop charged. // // They are the *mechanism* the fix has to be pinned on, and it is what a // whole-solve assertion cannot see: the cadence is denominated in charged // work, so a poll comes at the first loop pass that starts `kTermCheckWork` // units past the previous one, and the contract is // `max_gap < kTermCheckWork + max_iteration` (#173) -- the same residual // `dev/options.md` gives, one step plus `kTermCheckWork` units. It is // not `polls * kTermCheckWork >= effort`: every gap overshoots // `kTermCheckWork` by up to one pass, and those overshoots add up. Under // the retired step cadence a gap was 1000 steps, which on any instance // whose average step charges more than `kTermCheckWork / 1000` units breaks // the contract by a wide margin. Reading them needs no clock. struct DeadlinePollCounters { int64_t polls; int64_t effort; int64_t max_gap; int64_t max_iteration; }; void reset_deadline_poll_counters(); DeadlinePollCounters deadline_poll_counters(); // Called by `LocalMipWorker::run_attempt`: once per wall-clock poll, and // once at the end of each attempt with the effort that attempt charged and // its largest poll gap and loop pass. void note_deadline_poll(); void note_attempt_effort(int64_t effort_charged, int64_t max_gap, int64_t max_iteration); // Runs N continuous `parallel::for_each` workers with per-worker // self-termination. Worker 0 starts from the unperturbed incumbent; // workers 1..N-1 start from perturbed incumbents. Stalled workers are // restarted from the pool's best solution with fresh perturbation. Set // `threads=1` for a single worker whose behaviour is reproducible under // a fixed `random_seed`. // // Implements the uniform runner contract; see heuristic_context.h. // // The effort returned covers the cold-start construction sweep as well // as the search itself. DispatchOutcome run(const ProblemView& problem, const HeuristicBudget& budget, ExecutionContext& exec, SolutionSink& sink); // One LocalMipWorker slot on the calling thread until `exec` says stop // (#171), rebuilt whenever it stalls, from `source` first and with the // same fresh perturbation as any restart. See `run_until_stopped` in // heuristic_context.h for the contract. [[nodiscard]] size_t run_until_stopped(const ProblemView& problem, const HeuristicBudget& budget, const ExecutionContext& exec, int worker, const RestartSource& source, SolutionSink& sink); } // namespace local_mip solution_sink.h =============== .. code-block:: c #pragma once #include "lp_data/HConst.h" #include "rng.h" #include "solution_pool.h" #include "worker_base.h" #include #include #include #include // A `kPoolCapacity` pool over columns of `integrality` // (`*ProblemView::integrality`), the mask diversity-aware admission measures // Hamming distance on. [[nodiscard]] std::shared_ptr make_solution_pool( const std::vector& integrality); // The one place a heuristic worker hands a solution back. // // Objectives are in the `ProblemView`'s minimisation form, offset included // (#170): the pool ranks lower as better, and for a maximisation model // every objective here is the negated original one. // // Holds the `SolutionPool` its workers share and the tag its entries are // attributed with, and counts what the pool accepted. The pool is its own // unless it was handed one: the sinks of long-lived heuristics running at // once share their owner's pool, each offering under its own tag (#333), // which the pool stores per entry. What happens to an accepted // solution beyond the pool is `on_accept`'s, which does nothing here: the // HiGHS adapter (`IncumbentSink`) submits it to the solver there, and a // caller running the workers on a model it owns (#170) overrides it to // take the solutions wherever it wants them. class SolutionSink { public: // A pool of its own, `make_solution_pool(integrality)`. `source` tags // everything offered. SolutionSink(const std::vector& integrality, int source); // Over `pool`, never null, which other sinks may share. SolutionSink(std::shared_ptr pool, int source); virtual ~SolutionSink() = default; SolutionSink(const SolutionSink&) = delete; SolutionSink& operator=(const SolutionSink&) = delete; // What one offer did, in the two senses that matter (#116). // // `accepted` is the pool's admission verdict, unchanged since #111. // `improved_incumbent` is whether the offer moved the best objective // the solve knows — decided by `SolutionPool` against the best it held // before the insertion, which is the same thing while a presolve // dispatch runs: the sink seeds the pool from the incumbent and every // solution that reaches HiGHS goes through the pool first, so nothing // can lower the incumbent behind the pool's back. Deriving it there // rather than from a solver field is also what keeps it off a worker // thread, where reading `mipdata` races `addIncumbent` (#98/#99). struct OfferResult { bool accepted = false; bool improved_incumbent = false; }; // Offer a candidate solution. When the pool accepts it, `on_accept` // has already run, from inside this call. Safe to call concurrently // from any worker. // // Two verdicts, because there are two questions and #111 answered the // wrong one with the right mechanism. Every presolve worker used to // drop the pool's answer and substitute a worker-local notion ("I beat // my own best"), which resets to nothing on rebuild, so the staleness // counters the patience gates read were cleared by solutions the pool // had refused: on `fpr/flugpl` at one worker, 2,785,359 effort against // a 69,632 ceiling with exactly one accepted incumbent, i.e. 39 // ceilings' worth of free resets. #111 pointed the gates at // `accepted`, which fixed the refusals but left the pool's *admission // policy* driving them — it keeps a top-K, so a heuristic beating its // own worst entry resets staleness forever. #113's probe put a number // on the difference: 233 instances, presolve-only, 30 s, 16 workers, // FPR earns ~3.3 M acceptances against 590 incumbent improvements, // Scylla 367,801 against 374. Five orders of magnitude, so a patience // calibrated on improvements cannot be spent against a gate that // resets on acceptances. // // So `OfferResult::improved_incumbent` is what every staleness gate // but FJ's worker-level one reads (#116; FJ's reads FJ's own counter, // #191), and `accepted` is what `accepted()`, `[Heur] found` // and `[HeurSol] accepted` keep reporting — production, in the sense // of "a feasible solution worth keeping", is still the pool's call and // external tooling reads it as that. // // `[[nodiscard]]` since #111, and returning a struct rather than a // bool is deliberate: it makes every gate site name which fact it // reads instead of inheriting whichever one `offer` happened to mean. // The two deliberate discards are spelled `static_cast` with a // reason at the call site. // // Both flags are computed inside `SolutionPool`'s own lock — which is // where the pre-offer best is race-free — and returned by value, so // reading them adds no shared state (#98/#99). // // `effort_at` is the offering worker's own charged effort at the moment // of the offer — the counter that worker's *own* patience gate reads, so a // difference between two `effort_at` values is directly comparable with // `HeuristicBudget::worker_stale` (#106). Every worker keeps such a // counter already; none of them is recomputed or redefined for this, // and Scylla's stays the amortised (PDLP cost ÷ N) one its gate uses. // It is *not* monotone across a dispatch: FJ, LocalMIP and Scylla all // rebuild a retired worker in place and a rebuild starts a fresh // counter at zero, so the per-dispatch sequence is sawtooth. // // `trace` names the worker slot the offer comes from and carries the // charge of that slot's retired occupants, so `trace.at(effort_at)` is // monotone across rebuilds; see `WorkerTrace` in worker_base.h. [[nodiscard]] OfferResult offer(double objective, const std::vector& solution, const WorkerTrace& trace, size_t effort_at); // Number of offers the pool has accepted since construction. The // `found` field of the `[Heur]` instrumentation line (issue #95) is // this counter moving across one heuristic's dispatch; the sink is // the only place that knows, because a worker's return value is its // effort and nothing else. Relaxed loads are enough: the dispatching // thread reads it either side of a joined parallel region, so the // join already provides the ordering. // // "Accepted by the pool", not "improved the incumbent": the pool also // admits a solution within `kDiversityObjTolerance` of the best when // it is structurally diverse. `found=1` therefore means the heuristic // produced a feasible solution worth keeping, which is what the // `found` field of the `[Heur]` line reports. [[nodiscard]] size_t accepted() const { return accepted_.load(std::memory_order_relaxed); } // Restart material for a worker beginning a fresh attempt. Both are // thread-safe (the pool takes its own lock). bool get_restart(Rng& rng, std::vector& out, SolutionPool::RestartPolicy policy = SolutionPool::RestartPolicy::kMixed) { return pool_->get_restart(rng, out, policy); } bool copy_best(std::vector& out) { return pool_->copy_best(out); } // The pool's best by pointer (`SolutionPool::best_ref`). [[nodiscard]] SolutionPool::SolutionPtr best_ref() { return pool_->best_ref(); } // The pool's entries by pointer, best first (`SolutionPool::entry_refs`). void entry_refs(std::vector& out) { pool_->entry_refs(out); } // The pool's best objective, or `kHighsInf` while it holds nothing. // Thread-safe (the pool lock), so poll it at a heuristic's own polling // cadence, not per step. [[nodiscard]] double best_objective() { return pool_->snapshot().best_objective; } protected: // Called once per accepted offer, on the offering worker's thread, // after the pool lock is released and before `offer` returns — so // concurrently from every worker of a dispatch, and it must be // thread-safe. `source` is the tag the entry was stored with. virtual void on_accept(double objective, const std::vector& solution, int source, const WorkerTrace& trace, size_t effort_at); // Never null. std::shared_ptr pool_; // Tag for everything offered. Written only between parallel regions // (`IncumbentSink::set_source`). int source_; private: std::atomic accepted_{0}; };