diff --git a/Cargo.lock b/Cargo.lock index 06062facc..aeee9ae62 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -595,6 +595,7 @@ dependencies = [ "asap-types", "good_lp", "highs", + "highs-sys", "serde", "serde_json", "thiserror 2.0.18", diff --git a/crates/stage1-pass2-reuse-candidates/src/dead_candidates.rs b/crates/stage1-pass2-reuse-candidates/src/dead_candidates.rs index f2e72c6f1..273339bcb 100644 --- a/crates/stage1-pass2-reuse-candidates/src/dead_candidates.rs +++ b/crates/stage1-pass2-reuse-candidates/src/dead_candidates.rs @@ -42,9 +42,69 @@ pub(crate) fn dead_candidate_set( /// Per dead candidate, why, judged against those dead before it: cut off /// from an input (`Some(input)`), or without a live consumer. +/// +/// Elimination goes in rounds, each judging against the candidates dead +/// before it. The first round checks every candidate; a later one checks +/// only the candidates an edge links to one that died in the round before +/// (a candidate with no such edge is judged against the same dead set as +/// before, so it stays alive). The rounds, and so the reasons, are those +/// of rescanning every candidate each round. fn dead_candidates( memo: &Memo, graph: &EdgeGraph<'_>, +) -> BTreeMap> { + let outputs = memo.root_groups(); + let mut to_check: BTreeSet = memo + .groups() + .iter() + .enumerate() + .flat_map(|(group, memo_group)| { + (0..memo_group.candidates.len()).map(move |index_in_group| CandidateForMemoGroupId { + group: MemoGroupId(group as u32), + index_in_group, + }) + }) + .collect(); + let mut dead: BTreeMap> = BTreeMap::new(); + while !to_check.is_empty() { + let newly_dead: Vec<(CandidateForMemoGroupId, Option)> = to_check + .iter() + .copied() + .filter_map(|candidate| { + if let Some(input) = graph.cut_off_input(memo, candidate, &dead) { + Some((candidate, Some(input))) + } else if !outputs.contains(&candidate.group) + && !graph.has_live_consumer(candidate, &dead) + { + Some((candidate, None)) + } else { + None + } + }) + .collect(); + dead.extend(newly_dead.iter().copied()); + to_check = newly_dead + .iter() + .flat_map(|&(candidate, _)| graph.neighbours(candidate)) + .filter(|neighbour| !dead.contains_key(neighbour)) + .collect(); + } + #[cfg(test)] + assert_eq!( + dead, + dead_candidates_by_rescanning(memo, graph), + "the rounds of rescanning every candidate" + ); + dead +} + +/// [`dead_candidates`] rescanning every candidate each round: the +/// reference a faster elimination must agree with. The tests check the +/// two agree on every memo they eliminate over. +#[cfg(test)] +fn dead_candidates_by_rescanning( + memo: &Memo, + graph: &EdgeGraph<'_>, ) -> BTreeMap> { let outputs = memo.root_groups(); let all: Vec = memo @@ -88,6 +148,8 @@ fn dead_candidates( struct EdgeGraph<'a> { by_producer: HashMap>, by_consumer_input: HashMap<(CandidateForMemoGroupId, usize), Vec<&'a CandidateEdge>>, + /// Per consumer, the producers of its edges, on every input. + producers_of: HashMap>, } impl<'a> EdgeGraph<'a> { @@ -95,6 +157,7 @@ impl<'a> EdgeGraph<'a> { let mut graph = Self { by_producer: HashMap::new(), by_consumer_input: HashMap::new(), + producers_of: HashMap::new(), }; for edge in edges { graph @@ -107,10 +170,36 @@ impl<'a> EdgeGraph<'a> { .entry((edge.consumer, edge.input)) .or_default() .push(edge); + graph + .producers_of + .entry(edge.consumer) + .or_default() + .push(edge.producer); } graph } + /// The candidates an edge links to `candidate`: its consumers and its + /// producers. Only their judgement can change when `candidate` dies. + fn neighbours( + &self, + candidate: CandidateForMemoGroupId, + ) -> impl Iterator + '_ { + let consumers = self + .by_producer + .get(&candidate) + .into_iter() + .flatten() + .map(|edge| edge.consumer); + let producers = self + .producers_of + .get(&candidate) + .into_iter() + .flatten() + .copied(); + consumers.chain(producers) + } + /// Whether `candidate` has a satisfied edge into a consumer not in `dead`. fn has_live_consumer( &self, diff --git a/crates/stage1-pass2-reuse-candidates/src/evaluation_grids.rs b/crates/stage1-pass2-reuse-candidates/src/evaluation_grids.rs index bb8265802..6096b6537 100644 --- a/crates/stage1-pass2-reuse-candidates/src/evaluation_grids.rs +++ b/crates/stage1-pass2-reuse-candidates/src/evaluation_grids.rs @@ -25,16 +25,26 @@ pub(crate) fn evaluation_period_ms_per_query( ) -> Vec>> { let mut periods_ms: Vec>> = vec![BTreeMap::new(); memo.groups().len()]; + // A group waits at most once: its periods are read when it is taken, + // so a change while it waits is passed on then. The periods are a + // least fixpoint of gcd merges, the same in any order. let mut pending = Vec::new(); + let mut waiting = vec![false; memo.groups().len()]; + fn wait(pending: &mut Vec, waiting: &mut [bool], group: MemoGroupId) { + if !std::mem::replace(&mut waiting[group.0 as usize], true) { + pending.push(group); + } + } for (query, memo_query) in memo.queries().iter().enumerate() { let period_ms = query_evaluation_period_ms(entries, query); for &root in memo_query.root.operator_refs() { if merge(&mut periods_ms[root.0 as usize], query, period_ms) { - pending.push(root); + wait(&mut pending, &mut waiting, root); } } } while let Some(group) = pending.pop() { + waiting[group.0 as usize] = false; let periods_here_ms = periods_ms[group.0 as usize].clone(); for candidate in &memo.groups()[group.0 as usize].candidates { let operator = &candidate.expression.operator; @@ -50,7 +60,7 @@ pub(crate) fn evaluation_period_ms_per_query( for (&query, &period_ms) in &periods_here_ms { let below_ms = subquery_resolution_ms.unwrap_or(period_ms); if merge(&mut periods_ms[child.0 as usize], query, below_ms) { - pending.push(child); + wait(&mut pending, &mut waiting, child); } } } diff --git a/crates/stage3-plan-selection/Cargo.toml b/crates/stage3-plan-selection/Cargo.toml index dfeb3d041..169e08054 100644 --- a/crates/stage3-plan-selection/Cargo.toml +++ b/crates/stage3-plan-selection/Cargo.toml @@ -19,4 +19,6 @@ good_lp = { version = "=1.15.3", default-features = false, features = ["highs"] highs = "=2.4.0" [dev-dependencies] +# Reads the MPS files of the block-split check (`independent_blocks`). +highs-sys = "=1.15.0" asap-types = { path = "../types", features = ["test-support"] } diff --git a/crates/stage3-plan-selection/src/milp/model/independent_blocks.rs b/crates/stage3-plan-selection/src/milp/model/independent_blocks.rs new file mode 100644 index 000000000..b3462eccb --- /dev/null +++ b/crates/stage3-plan-selection/src/milp/model/independent_blocks.rs @@ -0,0 +1,371 @@ +//! The selection MILP split into its independent blocks, each solved by +//! HiGHS on its own. +//! +//! Two columns are in one block when a row reads both, directly or through +//! other columns; a row is in the block of its columns. Blocks share no +//! column and no row, so the MILP's optimum is the sum of the blocks' +//! optima and the plan is the union of their selections: the split is +//! exact. It happens after the model is built, so every sharing the model +//! offers stays in it; a block is only a part of the model no row links +//! to the rest. +//! +//! Example: a workload of PromQL queries over `data` and SQL queries over +//! `http` and `flows`, no state read across sources, has (at least) three +//! blocks, one per source. Solved together, HiGHS spends most of its time +//! on the hardest block's root cuts and heuristics while carrying the +//! others; solved apart, the easy blocks finish in milliseconds and the +//! blocks run on parallel threads. +//! +//! A column no row reads ([`MilpBlocks::loose_columns`]) takes its +//! cheapest bound; a row that reads no column +//! ([`MilpBlocks::rows_without_columns`]) is checked against 0. + +use std::sync::atomic::{AtomicUsize, Ordering}; + +use good_lp::{Constraint, Expression, IntoAffineExpression, ProblemVariables}; +use highs::HighsModelStatus; + +/// One column of a [`Milp`]: its objective coefficient, bounds and +/// integrality. +#[derive(Debug, Clone, PartialEq)] +pub(super) struct MilpColumn { + pub(super) cost: f64, + pub(super) lower: f64, + pub(super) upper: f64, + pub(super) integer: bool, +} + +/// One row of a [`Milp`]: `lower` ≤ Σ coefficient × column ≤ `upper`, +/// its `(column, coefficient)` entries ascending by column. +#[derive(Debug, Clone, PartialEq)] +pub(super) struct MilpRow { + pub(super) lower: f64, + pub(super) upper: f64, + pub(super) entries: Vec<(usize, f64)>, +} + +/// A minimization MILP as HiGHS takes it. +#[derive(Debug, Clone, Default, PartialEq)] +pub(super) struct Milp { + pub(super) columns: Vec, + pub(super) rows: Vec, +} + +impl Milp { + /// The MILP good_lp hands HiGHS for minimizing `objective` over + /// `problem`'s variables under `constraints`: a column per variable, in + /// order, and a row per constraint, in order (good_lp keeps a + /// constraint as `expression <= 0` or `expression == 0`). + pub(super) fn of( + problem: &ProblemVariables, + objective: &Expression, + constraints: &[Constraint], + ) -> Self { + let column_of = super::column_of(problem); + let mut columns: Vec = problem + .iter_variables_with_def() + .map(|(_, definition)| MilpColumn { + cost: 0.0, + lower: definition.get_min(), + upper: definition.get_max(), + integer: definition.is_integer(), + }) + .collect(); + for (variable, coefficient) in objective.linear_coefficients() { + columns[column_of[&variable]].cost += coefficient; + } + let rows = constraints + .iter() + .map(|constraint| { + let expression = constraint.expression(); + let upper = -expression.constant(); + let mut entries: Vec<(usize, f64)> = expression + .linear_coefficients() + .map(|(variable, coefficient)| (column_of[&variable], coefficient)) + .collect(); + entries.sort_unstable_by_key(|&(column, _)| column); + MilpRow { + lower: if constraint.is_equality() { + upper + } else { + f64::NEG_INFINITY + }, + upper, + entries, + } + }) + .collect(); + Milp { columns, rows } + } +} + +/// One independent block: its columns and rows, ascending. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) struct MilpBlock { + pub(super) columns: Vec, + pub(super) rows: Vec, +} + +/// A [`Milp`]'s independent blocks, ordered by their first column, with +/// the columns and rows in none. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) struct MilpBlocks { + pub(super) blocks: Vec, + /// The columns no row reads, ascending. + pub(super) loose_columns: Vec, + /// The rows that read no column, ascending. + pub(super) rows_without_columns: Vec, +} + +/// The independent blocks of `milp`. +pub(super) fn independent_blocks(milp: &Milp) -> MilpBlocks { + let column_count = milp.columns.len(); + // Union-find over the columns: every row joins its columns. + let mut parent: Vec = (0..column_count).collect(); + fn root(parent: &mut [usize], mut column: usize) -> usize { + while parent[column] != column { + parent[column] = parent[parent[column]]; + column = parent[column]; + } + column + } + for row in &milp.rows { + if let Some(&(first, _)) = row.entries.first() { + for &(column, _) in &row.entries[1..] { + let (a, b) = (root(&mut parent, first), root(&mut parent, column)); + if a != b { + parent[a.max(b)] = a.min(b); + } + } + } + } + let mut has_row = vec![false; column_count]; + let mut rows_without_columns = Vec::new(); + for (index, row) in milp.rows.iter().enumerate() { + match row.entries.first() { + Some(&(first, _)) => has_row[root(&mut parent, first)] = true, + None => rows_without_columns.push(index), + } + } + // Blocks in the order of their first column. + let mut block_of_root: Vec> = vec![None; column_count]; + let mut blocks: Vec = Vec::new(); + let mut loose_columns = Vec::new(); + for column in 0..column_count { + let at = root(&mut parent, column); + if !has_row[at] { + loose_columns.push(column); + continue; + } + let block = *block_of_root[at].get_or_insert_with(|| { + blocks.push(MilpBlock { + columns: Vec::new(), + rows: Vec::new(), + }); + blocks.len() - 1 + }); + blocks[block].columns.push(column); + } + for (index, row) in milp.rows.iter().enumerate() { + if let Some(&(first, _)) = row.entries.first() { + let block = block_of_root[root(&mut parent, first)].expect("a block per row's columns"); + blocks[block].rows.push(index); + } + } + MilpBlocks { + blocks, + loose_columns, + rows_without_columns, + } +} + +/// How HiGHS solves each block. +#[derive(Debug, Clone, Copy, PartialEq, Default)] +pub(super) struct HighsSettings { + /// HiGHS's primal and MIP feasibility tolerance; its default when + /// `None`. + pub(super) feasibility_tolerance: Option, + /// Solve the LP relaxation instead of the MILP. + pub(super) relaxation: bool, +} + +/// A solved [`Milp`]: every column's value and the objective. +#[derive(Debug, Clone, PartialEq)] +pub(super) struct SolvedMilp { + pub(super) columns: Vec, + pub(super) objective: f64, +} + +/// Why a [`Milp`] has no solution: the status of the first block (in +/// block order) without one, or HiGHS's failure. +#[derive(Debug, Clone, PartialEq)] +pub(super) enum MilpSolveError { + Status(HighsModelStatus), + Solver(String), +} + +/// The most threads that solve blocks at once. Each HiGHS solve runs on one +/// thread, so a plan is the same whatever the thread count. +pub(super) const MOST_BLOCK_SOLVER_THREADS: usize = 4; + +/// Solves `milp` block by block (`blocks` is [`independent_blocks`] of +/// it), at gap 0, on up to `threads` threads; the result is assembled in +/// block order, so it does not depend on which thread solved which block. +pub(super) fn solve_by_blocks( + milp: &Milp, + blocks: &MilpBlocks, + settings: HighsSettings, + threads: usize, +) -> Result { + // The largest blocks first, so a large block does not start last. + let mut order: Vec = (0..blocks.blocks.len()).collect(); + order.sort_by_key(|&block| std::cmp::Reverse(blocks.blocks[block].columns.len())); + let threads = threads.clamp(1, blocks.blocks.len().max(1)); + let mut solved: Vec> = vec![None; blocks.blocks.len()]; + if threads == 1 { + for &block in &order { + solved[block] = Some(solve_block(milp, &blocks.blocks[block], settings)); + } + } else { + let next = AtomicUsize::new(0); + let per_thread: Vec> = std::thread::scope(|scope| { + let workers: Vec<_> = (0..threads) + .map(|_| { + scope.spawn(|| { + let mut done = Vec::new(); + while let Some(&block) = order.get(next.fetch_add(1, Ordering::Relaxed)) { + done.push((block, solve_block(milp, &blocks.blocks[block], settings))); + } + done + }) + }) + .collect(); + workers + .into_iter() + .map(|worker| worker.join().expect("a block solver thread")) + .collect() + }); + for (block, result) in per_thread.into_iter().flatten() { + solved[block] = Some(result); + } + } + let mut columns = vec![0.0; milp.columns.len()]; + let mut objective = 0.0; + // Assembled in block order, whichever thread solved a block. + for (block, result) in blocks.blocks.iter().zip(solved) { + let (values, block_objective) = result.expect("every block solved")?; + for (&column, value) in block.columns.iter().zip(values) { + columns[column] = value; + } + objective += block_objective; + } + for &column in &blocks.loose_columns { + let MilpColumn { + cost, lower, upper, .. + } = milp.columns[column]; + let value = if cost > 0.0 { + lower + } else if cost < 0.0 { + upper + } else { + 0.0_f64.clamp(lower, upper) + }; + if !value.is_finite() { + return Err(MilpSolveError::Status(HighsModelStatus::Unbounded)); + } + columns[column] = value; + objective += cost * value; + } + for &row in &blocks.rows_without_columns { + let MilpRow { lower, upper, .. } = milp.rows[row]; + if lower > HIGHS_PRIMAL_FEASIBILITY_TOLERANCE || upper < -HIGHS_PRIMAL_FEASIBILITY_TOLERANCE + { + return Err(MilpSolveError::Status(HighsModelStatus::Infeasible)); + } + } + Ok(SolvedMilp { columns, objective }) +} + +/// `milp` as one HiGHS problem, every column and row in one block: what +/// the planner solved before the split, kept for tests that compare the +/// two. +#[cfg(test)] +pub(super) fn solve_whole( + milp: &Milp, + settings: HighsSettings, +) -> Result { + let block = MilpBlock { + columns: (0..milp.columns.len()).collect(), + rows: (0..milp.rows.len()).collect(), + }; + let (columns, objective) = solve_block(milp, &block, settings)?; + Ok(SolvedMilp { columns, objective }) +} + +/// HiGHS's default primal feasibility tolerance (absolute), to which a +/// row that reads no column is checked against 0. +const HIGHS_PRIMAL_FEASIBILITY_TOLERANCE: f64 = 1e-7; + +/// A solved block's column values (in its column order) and objective. +type BlockResult = Result<(Vec, f64), MilpSolveError>; + +/// Solves `block` of `milp` as its own HiGHS problem: its columns and rows +/// in their order in `milp`, at gap 0 on one thread. +fn solve_block(milp: &Milp, block: &MilpBlock, settings: HighsSettings) -> BlockResult { + let mut problem = highs::RowProblem::default(); + let mut position = std::collections::HashMap::with_capacity(block.columns.len()); + let columns: Vec = block + .columns + .iter() + .enumerate() + .map(|(at, &column)| { + position.insert(column, at); + let MilpColumn { + cost, + lower, + upper, + integer, + } = milp.columns[column]; + problem.add_column_with_integrality(cost, lower..=upper, integer) + }) + .collect(); + for &row in &block.rows { + let MilpRow { + lower, + upper, + ref entries, + } = milp.rows[row]; + problem.add_row( + lower..=upper, + entries + .iter() + .map(|&(column, coefficient)| (columns[position[&column]], coefficient)), + ); + } + let mut model = problem + .try_optimise(highs::Sense::Minimise) + .map_err(|status| MilpSolveError::Solver(format!("{status:?}")))?; + model.set_option("mip_rel_gap", 0.0); + model.set_option("mip_abs_gap", 0.0); + model.set_option("output_flag", false); + model.set_option("threads", 1); + if let Some(tolerance) = settings.feasibility_tolerance { + model.set_option("primal_feasibility_tolerance", tolerance); + model.set_option("mip_feasibility_tolerance", tolerance); + } + if settings.relaxation { + model.set_option("solve_relaxation", true); + } + let solved = model + .try_solve() + .map_err(|status| MilpSolveError::Solver(format!("{status:?}")))?; + if settings.relaxation && solved.status() != HighsModelStatus::Optimal { + return Err(MilpSolveError::Status(solved.status())); + } + let values = + super::solution_columns(&solved, block.columns.len()).map_err(MilpSolveError::Status)?; + Ok((values, solved.objective_value())) +} + +#[cfg(test)] +mod tests; diff --git a/crates/stage3-plan-selection/src/milp/model/independent_blocks/tests.rs b/crates/stage3-plan-selection/src/milp/model/independent_blocks/tests.rs new file mode 100644 index 000000000..27a30d1a2 --- /dev/null +++ b/crates/stage3-plan-selection/src/milp/model/independent_blocks/tests.rs @@ -0,0 +1,439 @@ +//! Block detection, and the optimum solved block by block against the +//! same MILP solved whole: on small generated MILPs, and (ignored, run by +//! hand) on MILPs the planner dumped for paper workloads. + +use std::time::Instant; + +use good_lp::{constraint, variable, Expression, ProblemVariables}; + +use super::*; + +const INF: f64 = f64::INFINITY; + +fn binary(cost: f64) -> MilpColumn { + MilpColumn { + cost, + lower: 0.0, + upper: 1.0, + integer: true, + } +} + +fn at_least(lower: f64, entries: &[(usize, f64)]) -> MilpRow { + MilpRow { + lower, + upper: INF, + entries: entries.to_vec(), + } +} + +/// Whether `a` and `b` agree to `relative` of the larger magnitude (at +/// least 1). +fn close(a: f64, b: f64, relative: f64) -> bool { + (a - b).abs() <= relative * a.abs().max(b.abs()).max(1.0) +} + +#[test] +fn columns_linked_through_rows_are_one_block() { + // Rows 0 and 1 link columns 0, 2 and 4 (through column 2); row 2 links + // 1 and 3; no row reads column 5; row 3 reads no column. + let milp = Milp { + columns: (0..6).map(|j| binary(j as f64)).collect(), + rows: vec![ + at_least(1.0, &[(0, 1.0), (2, 1.0)]), + at_least(1.0, &[(2, 1.0), (4, 1.0)]), + at_least(1.0, &[(1, 1.0), (3, 1.0)]), + at_least(-1.0, &[]), + ], + }; + assert_eq!( + independent_blocks(&milp), + MilpBlocks { + blocks: vec![ + MilpBlock { + columns: vec![0, 2, 4], + rows: vec![0, 1], + }, + MilpBlock { + columns: vec![1, 3], + rows: vec![2], + }, + ], + loose_columns: vec![5], + rows_without_columns: vec![3], + } + ); +} + +#[test] +fn a_row_over_every_column_makes_one_block() { + let milp = Milp { + columns: (0..4).map(|_| binary(1.0)).collect(), + rows: vec![ + at_least(1.0, &[(0, 1.0), (1, 1.0)]), + at_least(1.0, &[(2, 1.0), (3, 1.0)]), + at_least(2.0, &[(0, 1.0), (1, 1.0), (2, 1.0), (3, 1.0)]), + ], + }; + let blocks = independent_blocks(&milp); + assert_eq!( + blocks.blocks, + vec![MilpBlock { + columns: vec![0, 1, 2, 3], + rows: vec![0, 1, 2], + }] + ); + assert!(blocks.loose_columns.is_empty()); +} + +#[test] +fn a_good_lp_model_becomes_highs_columns_and_rows() { + let mut problem = ProblemVariables::new(); + let x = problem.add(variable().binary()); + let y = problem.add(variable().min(0.0).max(10.0)); + let z = problem.add(variable().min(0.0)); + let objective: Expression = 3.0 * x + 2.0 * y; + let constraints = vec![ + constraint!(y + x >= 1.0), + constraint!(y <= 4.0), + constraint!(x == 1.0), + ]; + let milp = Milp::of(&problem, &objective, &constraints); + assert_eq!( + milp.columns, + vec![ + MilpColumn { + cost: 3.0, + lower: 0.0, + upper: 1.0, + integer: true, + }, + MilpColumn { + cost: 2.0, + lower: 0.0, + upper: 10.0, + integer: false, + }, + MilpColumn { + cost: 0.0, + lower: 0.0, + upper: INF, + integer: false, + }, + ] + ); + // good_lp keeps every row as `expression <= 0`: `y + x >= 1` is + // `1 - x - y <= 0`, so `-x - y <= -1`. + assert_eq!( + milp.rows, + vec![ + MilpRow { + lower: -INF, + upper: -1.0, + entries: vec![(0, -1.0), (1, -1.0)], + }, + MilpRow { + lower: -INF, + upper: 4.0, + entries: vec![(1, 1.0)], + }, + MilpRow { + lower: 1.0, + upper: 1.0, + entries: vec![(0, 1.0)], + }, + ] + ); + let _ = z; +} + +/// A deterministic generator (64-bit LCG) for the generated MILPs. +struct Lcg(u64); + +impl Lcg { + fn next(&mut self) -> f64 { + self.0 = self + .0 + .wrapping_mul(6_364_136_223_846_793_005) + .wrapping_add(1_442_695_040_888_963_407); + (self.0 >> 11) as f64 / (1u64 << 53) as f64 + } +} + +/// `block_count` covering blocks of 12 binary columns and 8 rows each +/// (every row needs at least 2 of its 4 to 6 columns, a row of one block +/// may also reach into the next when `linked`), plus a continuous column +/// no row reads; costs are random, so the optimum is unique. +fn covering_milp(seed: u64, block_count: usize, linked: bool) -> Milp { + let mut random = Lcg(seed); + let per_block = 12; + let mut milp = Milp::default(); + for _ in 0..block_count * per_block { + milp.columns.push(binary(1.0 + 9.0 * random.next())); + } + for block in 0..block_count { + for row in 0..8 { + let mut columns: Vec = (0..4 + (row % 3)) + .map(|_| block * per_block + (random.next() * per_block as f64) as usize) + .collect(); + if linked && row == 0 && block + 1 < block_count { + columns.push((block + 1) * per_block); + } + columns.sort_unstable(); + columns.dedup(); + let entries: Vec<(usize, f64)> = columns + .into_iter() + .map(|column| (column, 1.0 + random.next())) + .collect(); + milp.rows.push(at_least(2.0, &entries)); + } + } + milp.columns.push(MilpColumn { + cost: 0.5, + lower: 0.0, + upper: 3.0, + integer: false, + }); + milp +} + +#[test] +fn solving_block_by_block_finds_the_whole_models_optimum() { + for seed in 1..=5 { + let milp = covering_milp(seed, 6, false); + let blocks = independent_blocks(&milp); + assert_eq!(blocks.blocks.len(), 6, "seed {seed}"); + let whole = solve_whole(&milp, HighsSettings::default()).unwrap(); + for threads in [1, MOST_BLOCK_SOLVER_THREADS] { + let split = solve_by_blocks(&milp, &blocks, HighsSettings::default(), threads).unwrap(); + assert!( + close(split.objective, whole.objective, 1e-9), + "seed {seed}, {threads} threads: {} vs {}", + split.objective, + whole.objective + ); + assert_eq!( + split.columns, whole.columns, + "seed {seed}, {threads} threads" + ); + } + } +} + +#[test] +fn linked_blocks_are_solved_as_one() { + let milp = covering_milp(7, 4, true); + let blocks = independent_blocks(&milp); + assert_eq!(blocks.blocks.len(), 1); + let whole = solve_whole(&milp, HighsSettings::default()).unwrap(); + let split = solve_by_blocks(&milp, &blocks, HighsSettings::default(), 2).unwrap(); + assert!(close(split.objective, whole.objective, 1e-9)); + assert_eq!(split.columns, whole.columns); +} + +#[test] +fn the_lp_relaxation_block_by_block_is_the_whole_relaxation() { + let milp = covering_milp(11, 5, false); + let blocks = independent_blocks(&milp); + let relaxation = HighsSettings { + relaxation: true, + ..HighsSettings::default() + }; + let whole = solve_whole(&milp, relaxation).unwrap(); + let split = solve_by_blocks(&milp, &blocks, relaxation, 3).unwrap(); + assert!(close(split.objective, whole.objective, 1e-9)); + let integral = solve_whole(&milp, HighsSettings::default()).unwrap(); + assert!(split.objective <= integral.objective + 1e-9); +} + +#[test] +fn a_loose_column_takes_its_cheapest_bound() { + let milp = Milp { + columns: vec![ + binary(1.0), + MilpColumn { + cost: -2.0, + lower: 0.0, + upper: 3.0, + integer: false, + }, + MilpColumn { + cost: 0.0, + lower: -1.0, + upper: 5.0, + integer: false, + }, + ], + rows: vec![at_least(1.0, &[(0, 1.0)])], + }; + let blocks = independent_blocks(&milp); + assert_eq!(blocks.loose_columns, vec![1, 2]); + let split = solve_by_blocks(&milp, &blocks, HighsSettings::default(), 1).unwrap(); + assert_eq!(split.columns, vec![1.0, 3.0, 0.0]); + assert!(close(split.objective, 1.0 - 6.0, 1e-12)); +} + +#[test] +fn an_infeasible_block_makes_the_milp_infeasible() { + let mut milp = covering_milp(3, 2, false); + // Column 0 is binary: it cannot reach 2. + milp.rows.push(at_least(2.0, &[(0, 1.0)])); + let blocks = independent_blocks(&milp); + assert_eq!( + solve_by_blocks(&milp, &blocks, HighsSettings::default(), 2), + Err(MilpSolveError::Status(HighsModelStatus::Infeasible)) + ); +} + +#[test] +fn a_row_without_columns_holds_only_when_its_bounds_contain_zero() { + let mut milp = covering_milp(5, 2, false); + milp.rows.push(at_least(-1.0, &[])); + let blocks = independent_blocks(&milp); + assert!(solve_by_blocks(&milp, &blocks, HighsSettings::default(), 1).is_ok()); + milp.rows.push(at_least(1.0, &[])); + let blocks = independent_blocks(&milp); + assert_eq!( + solve_by_blocks(&milp, &blocks, HighsSettings::default(), 1), + Err(MilpSolveError::Status(HighsModelStatus::Infeasible)) + ); +} + +#[test] +fn an_empty_milp_is_solved_with_objective_zero() { + let milp = Milp::default(); + let blocks = independent_blocks(&milp); + assert_eq!( + solve_by_blocks(&milp, &blocks, HighsSettings::default(), 4), + Ok(SolvedMilp { + columns: vec![], + objective: 0.0, + }) + ); +} + +/// The MILP of an MPS file, read by HiGHS. +fn milp_of_mps(path: &std::path::Path) -> Milp { + use highs_sys::*; + use std::ffi::CString; + let path = CString::new(path.to_str().unwrap()).unwrap(); + unsafe { + let highs = Highs_create(); + Highs_setBoolOptionValue(highs, c"output_flag".as_ptr(), 0); + assert_eq!(Highs_readModel(highs, path.as_ptr()), 0, "read {path:?}"); + let (n, m, nz) = ( + Highs_getNumCol(highs) as usize, + Highs_getNumRow(highs) as usize, + Highs_getNumNz(highs) as usize, + ); + let (mut num_col, mut num_row, mut num_nz, mut sense) = (0, 0, 0, 0); + let mut offset = 0.0; + let (mut cost, mut col_lower, mut col_upper) = (vec![0.0; n], vec![0.0; n], vec![0.0; n]); + let (mut row_lower, mut row_upper) = (vec![0.0; m], vec![0.0; m]); + let (mut start, mut index, mut value) = (vec![0; n + 1], vec![0; nz], vec![0.0; nz]); + let mut integrality = vec![0; n]; + // Column-wise matrix (a_format 1). + Highs_getLp( + highs, + 1, + &mut num_col, + &mut num_row, + &mut num_nz, + &mut sense, + &mut offset, + cost.as_mut_ptr(), + col_lower.as_mut_ptr(), + col_upper.as_mut_ptr(), + row_lower.as_mut_ptr(), + row_upper.as_mut_ptr(), + start.as_mut_ptr(), + index.as_mut_ptr(), + value.as_mut_ptr(), + integrality.as_mut_ptr(), + ); + Highs_destroy(highs); + assert_eq!(offset, 0.0); + start[n] = nz as HighsInt; + let mut rows: Vec = (0..m) + .map(|row| MilpRow { + lower: row_lower[row], + upper: row_upper[row], + entries: Vec::new(), + }) + .collect(); + for column in 0..n { + for k in start[column] as usize..start[column + 1] as usize { + rows[index[k] as usize].entries.push((column, value[k])); + } + } + Milp { + columns: (0..n) + .map(|column| MilpColumn { + cost: cost[column], + lower: col_lower[column], + upper: col_upper[column], + integer: integrality[column] == 1, + }) + .collect(), + rows, + } + } +} + +/// The MILPs the planner built for paper workloads (dumped as MPS by a +/// diagnostic build, `ASAP_STAGE3_MPS_DIR` holding `n100.mps`, `m8u.mps`, +/// `b100.mps`): solved block by block, the optimum equals the whole +/// model's to 1e-9 (relative). Slow (about a minute per model solved +/// whole); run with +/// `ASAP_STAGE3_MPS_DIR= cargo test --release -p asap-stage3-plan-selection --lib dumped -- --ignored --nocapture`. +#[test] +#[ignore = "needs ASAP_STAGE3_MPS_DIR and minutes of HiGHS time"] +fn dumped_planner_milps_have_the_whole_models_optimum() { + let directory = std::path::PathBuf::from( + std::env::var("ASAP_STAGE3_MPS_DIR").expect("ASAP_STAGE3_MPS_DIR"), + ); + for (name, blocks_with_rows_over_one_column) in + [("n100.mps", 3), ("m8u.mps", 3), ("b100.mps", 16)] + { + let milp = milp_of_mps(&directory.join(name)); + let started = Instant::now(); + let blocks = independent_blocks(&milp); + let split_ms = started.elapsed().as_millis(); + assert_eq!( + blocks + .blocks + .iter() + .filter(|block| block.columns.len() > 1) + .count(), + blocks_with_rows_over_one_column, + "{name}" + ); + let started = Instant::now(); + let split = solve_by_blocks( + &milp, + &blocks, + HighsSettings::default(), + MOST_BLOCK_SOLVER_THREADS, + ) + .unwrap(); + let split_solve_ms = started.elapsed().as_millis(); + let started = Instant::now(); + let whole = solve_whole(&milp, HighsSettings::default()).unwrap(); + let whole_solve_ms = started.elapsed().as_millis(); + eprintln!( + "{name}: {} columns, {} rows, {} blocks ({split_ms} ms to find); \ + whole {} in {whole_solve_ms} ms, by blocks {} in {split_solve_ms} ms", + milp.columns.len(), + milp.rows.len(), + blocks.blocks.len(), + whole.objective, + split.objective, + ); + assert!( + close(split.objective, whole.objective, 1e-9), + "{name}: {} vs {}", + split.objective, + whole.objective + ); + } +} diff --git a/crates/stage3-plan-selection/src/milp/model/mod.rs b/crates/stage3-plan-selection/src/milp/model/mod.rs index f64c116b6..05ceca150 100644 --- a/crates/stage3-plan-selection/src/milp/model/mod.rs +++ b/crates/stage3-plan-selection/src/milp/model/mod.rs @@ -20,10 +20,7 @@ use std::collections::{BTreeMap, HashMap, HashSet}; use std::time::Instant; -use good_lp::solvers::highs::highs; -use good_lp::{ - constraint, variable, Constraint, Expression, ProblemVariables, SolverModel, Variable, -}; +use good_lp::{constraint, variable, Constraint, Expression, ProblemVariables, Variable}; use asap_cost::{AnswerCache, KeptQueryTimeResults}; use asap_types::accuracy::FailureProbabilityBound; @@ -44,8 +41,13 @@ use super::retention::{ use super::upper_bound::dearer_than_a_feasible_plan; use crate::cost::ExecutionCosts; use crate::selectable::{Execution, QueryId, SelectableExecutions}; +use independent_blocks::{ + independent_blocks, solve_by_blocks, HighsSettings, Milp, MilpSolveError, + MOST_BLOCK_SOLVER_THREADS, +}; pub(crate) mod cluster; +mod independent_blocks; /// What the MILP is built over. #[derive(Clone, Copy)] @@ -597,7 +599,9 @@ pub(crate) struct SolvedSelection { pub(crate) variable_count: usize, pub(crate) constraint_count: usize, pub(crate) construction_ms: u64, - /// The time of every HiGHS solve, summed. + /// The wall time of every solve of the MILP, summed; one solve runs + /// its independent blocks on parallel threads + /// ([`independent_blocks::solve_by_blocks`]). pub(crate) solve_ms: u64, /// How many times HiGHS solved the MILP: 1, or 2 when the selection at /// HiGHS's default tolerances missed an accuracy target when checked @@ -674,7 +678,9 @@ pub(super) fn objective_scale(largest: f64) -> f64 { /// query-time scan is in $r_s$; $h_v$ in seconds, held as a share of its /// longest need, [`RetentionShare`]) under (A)–(F), [`use_constraints`], /// the raw-data rows of [`selection_cost_terms`], (R), (X) and (K), with HiGHS at gap 0 on one -/// thread. The executions dearer than a feasible plan +/// thread per independent block ([`independent_blocks`]: blocks share no +/// variable and no row, so solving them apart finds the same optimum), +/// up to [`MOST_BLOCK_SOLVER_THREADS`] blocks at once. The executions dearer than a feasible plan /// ([`dearer_than_a_feasible_plan`]) or dominated by their lifetime twin /// ([`dominated_by_lifetime_twin`]) are left out first (and a /// copy of an equivalent context shares its original's variables, @@ -802,19 +808,21 @@ pub(crate) fn solve_selection_reporting_lp_bound( let variable_count = problem.len(); let column_of = column_of(&problem); let constraint_count = constraints.len(); - let mut model = problem - .minimise(objective) - .using(highs) - .with_all(constraints) - .try_into_inner() - .map_err(|error| SelectionMilpError::Solver(error.to_string()))?; - model.set_option("mip_rel_gap", 0.0); - model.set_option("mip_abs_gap", 0.0); - model.set_option("output_flag", false); - model.set_option("threads", 1); + // Solved block by block ([`independent_blocks`]): blocks share no + // variable and no row, so the optimum is the whole model's. + let milp = Milp::of(&problem, &objective, &constraints); + let blocks = independent_blocks(&milp); + let mut highs_settings = HighsSettings::default(); + let threads = std::thread::available_parallelism() + .map_or(1, usize::from) + .min(MOST_BLOCK_SOLVER_THREADS); let construction_ms = started.elapsed().as_millis() as u64; // The LP relaxation's optimum, unscaled, when asked for: solved after - // the MILP, on its model, so the measurement cannot change the plan. + // the MILP, on the same blocks, so the measurement cannot change the + // plan. The executions left out before the model was built are left + // out exactly ([`dearer_than_a_feasible_plan`], + // [`dominated_by_lifetime_twin`]), so it still bounds the MILP's + // optimum from below. let mut lp_bound_per_second = None; let selectable = inputs.selectable; let executions = selectable.executions(); @@ -831,33 +839,36 @@ pub(crate) fn solve_selection_reporting_lp_bound( .failure_probability_bound(query.0), }; // The MILP's optimum, unscaled, to check against `plan_cost`. - let mut optimum_per_second = 0.0; + let mut optimum_per_second; let (selected, selected_edges, answering) = loop { let started = Instant::now(); - let solved = model - .try_solve() - .map_err(|status| SelectionMilpError::Solver(format!("{status:?}")))?; + let solved = solve_by_blocks(&milp, &blocks, highs_settings, threads); solve_ms += started.elapsed().as_millis() as u64; solve_count += 1; use highs::HighsModelStatus; // No node or solution limit is set, so a feasible plan is an // optimum. - let columns: Vec = match solution_columns(&solved, variable_count) { - Ok(columns) => columns, + let columns: Vec = match solved { + Ok(solved) => { + optimum_per_second = solved.objective / scale; + solved.columns + } // At LEAST_HIGHS_FEASIBILITY_TOLERANCE no plan meets every // target at the tighter tolerance; the first selection missed // this query by less than 1e-7. - Err(HighsModelStatus::Infeasible | HighsModelStatus::UnboundedOrInfeasible) => { + Err(MilpSolveError::Status( + HighsModelStatus::Infeasible | HighsModelStatus::UnboundedOrInfeasible, + )) => { return Err(match missed_at_default_tolerance { Some(query) => below_solver_precision(query), None => SelectionMilpError::Infeasible, }) } - Err(other) => return Err(SelectionMilpError::Solver(format!("{other:?}"))), + Err(MilpSolveError::Status(other)) => { + return Err(SelectionMilpError::Solver(format!("{other:?}"))) + } + Err(MilpSolveError::Solver(error)) => return Err(SelectionMilpError::Solver(error)), }; - if solved.status() != HighsModelStatus::ModelEmpty { - optimum_per_second = solved.objective_value() / scale; - } let chosen = |variable: Variable| columns[column_of[&variable]] > 0.5; let (selected, selected_edges) = selected_executions_and_edges(&variables, chosen); let answering = answering_executions(selectable, &variables, chosen); @@ -872,7 +883,17 @@ pub(crate) fn solve_selection_reporting_lp_bound( .map(|rules| rules.selection_meets_targets(inputs, &selected_edges, &answering)) else { if report_lp_bound { - lp_bound_per_second = lp_relaxation_objective(solved.into()).map(|lp| lp / scale); + lp_bound_per_second = solve_by_blocks( + &milp, + &blocks, + HighsSettings { + relaxation: true, + ..highs_settings + }, + threads, + ) + .ok() + .map(|relaxed| relaxed.objective / scale); } break (selected, selected_edges, answering); }; @@ -880,18 +901,7 @@ pub(crate) fn solve_selection_reporting_lp_bound( return Err(below_solver_precision(query)); } missed_at_default_tolerance = Some(query); - // Solving the same HiGHS model again offers the first selection as - // a starting solution; HiGHS checks it at the tighter tolerance and - // drops it when it misses (as here), so it cannot bias the result. - model = solved.into(); - model.set_option( - "primal_feasibility_tolerance", - LEAST_HIGHS_FEASIBILITY_TOLERANCE, - ); - model.set_option( - "mip_feasibility_tolerance", - LEAST_HIGHS_FEASIBILITY_TOLERANCE, - ); + highs_settings.feasibility_tolerance = Some(LEAST_HIGHS_FEASIBILITY_TOLERANCE); }; let (cost_per_second_without_request_overhead, retention_ms) = selection_cost_per_second(inputs, &selected, &selected_edges, &answering); @@ -926,17 +936,6 @@ pub(crate) fn solve_selection_reporting_lp_bound( }) } -/// The LP relaxation's objective of `model` (scaled as the model is), a -/// measurement: `None` when HiGHS fails or does not reach the optimum. -/// The executions left out before the model was built are left out -/// exactly ([`dearer_than_a_feasible_plan`], [`dominated_by_lifetime_twin`]), -/// so it still bounds the MILP's optimum from below. -fn lp_relaxation_objective(mut model: highs::Model) -> Option { - model.set_option("solve_relaxation", true); - let relaxed = model.try_solve().ok()?; - (relaxed.status() == highs::HighsModelStatus::Optimal).then(|| relaxed.objective_value()) -} - /// The cost per second of a selection, less the request overhead every /// plan pays: its executions (`selected`, by position in /// `SelectableExecutions::executions`) and edges (`edges`, by position in