Linearization and elimination
A density query is linearized at a batch of points into factored least-squares problems over its free quantities, by its residuals or by its information roots, and each problem is eliminated in square-root form on the host into a step, marginals, an evidence, draws, or a retirement's replacement; the Levenberg–Marquardt method iterates the steps to the mode.
Every method that reads a model as least squares rests on two pieces.
Linearization replaces a query’s negative log-density near a point with a sum of squared affine residuals and a linear term over the tangent coordinates of its free quantities.
Elimination then solves the problem those rows pose, or removes some of its variables from it.
A Gauss–Newton step, a Levenberg–Marquardt step, a Laplace approximation and a Kalman filter’s update all end in them.
skoro has them in two crates. skoro-elimination is the note elimination in square-root form as code, numbers and matrices alone. skoro-linearize turns a query into such problems, reading the roles that the normal binds.
This page shows each piece.
The mathematics is in the part of the notes on least squares and Gaussian approximations, from the mode a query’s minimizer seeks, through linearization and the Gauss–Newton step and the normal equations, to the Levenberg–Marquardt method, the Laplace approximation and Fisher scoring; a table pairs the optimizer’s names for each thing with the estimator’s.
Why skoro made each of its choices is in the entry.
The factored problem#
A problem is a sum of factors of rows over blocks of variables, with a linear term and a constant:
Which blocks each factor involves is its structure, kept apart from the numbers so that one structure serves many problems:
crates/skoro-elimination/src/structure.rs lines 10–18/// The factor structure: blocks of given dimensions, and for each factor the blocks it involves,
/// in increasing order.
#[derive(Clone, PartialEq, Debug)]
pub struct Structure {
dimensions: Vec<usize>,
factors: Vec<Vec<usize>>,
/// Where each block's coordinates start in the stacked tangent.
offsets: Vec<usize>,
}crates/skoro-elimination/src/problem.rs lines 5–29/// One factor's rows: `A_f`, its columns those of its blocks in the structure's order, and `b_f`.
#[derive(Clone, PartialEq, Debug)]
pub struct Rows {
pub a: Matrix,
pub b: Vec<f64>,
}
/// `½ λ τᵀ D τ`: `λ` and the positive diagonal `D`, one entry per coordinate.
#[derive(Clone, PartialEq, Debug)]
pub struct Damping {
pub lambda: f64,
pub diagonal: Vec<f64>,
}
/// A problem with a constant, `c + Σ_f ½|A_f τ_{K_f} - b_f|² + ηᵀτ`, over a structure.
#[derive(Clone, Debug)]
pub struct Problem {
structure: Arc<Structure>,
factors: Vec<Rows>,
/// `η`, stacked over all blocks, or `None`: absent by structure, and then exactly zero.
linear: Option<Vec<f64>>,
constant: f64,
/// The unit roundoff of the precision the rows were computed at, for the rank test.
roundoff: f64,
}A linear term that is absent is absent by structure, and then exactly zero, which is what keeps it from being solved at the square of the rows’ condition number when it is not there. Damping, the of a Levenberg–Marquardt step, is given at elimination and appended as rows, so it leaves the structure as it is.
Scheduling an elimination#
The order of elimination, the elimination tree and the junction tree of its cliques depend on the structure alone.
A Schedule computes them once:
crates/skoro-elimination/src/structure.rs lines 106–138/// Every block, in a COLAMD order of the block pattern.
pub fn all(structure: &Arc<Structure>) -> Result<Schedule, Error> {
let n = structure.blocks().len();
let order = colamd(structure, &vec![true; n]);
Ok(Schedule::build(structure, order, Vec::new()))
}
/// Every block but `keep`, which are kept: the schedule of a marginal on `keep`, laid out in
/// `keep`'s order (`Shape` for a block named twice or one that does not exist).
pub fn keeping(structure: &Arc<Structure>, keep: &[usize]) -> Result<Schedule, Error> {
let kept = distinct(structure, keep)?;
let include: Vec<bool> = kept.iter().map(|&k| !k).collect();
let order = colamd(structure, &include);
Ok(Schedule::build(structure, order, keep.to_vec()))
}
/// The blocks `eliminate` alone, from the factors joined to them: the schedule of a
/// replacement, the others kept in increasing order (`Shape` as `keeping`).
pub fn eliminating(structure: &Arc<Structure>, eliminate: &[usize]) -> Result<Schedule, Error> {
let include = distinct(structure, eliminate)?;
let order = colamd(structure, &include);
let kept = (0..include.len()).filter(|&k| !include[k]).collect();
Ok(Schedule::build(structure, order, kept))
}
/// The blocks of `order` eliminated in that order, as far as the junction tree allows, and
/// the others kept in increasing order: for the tests of order-independence (`Shape` as
/// `keeping`).
pub fn in_order(structure: &Arc<Structure>, order: Vec<usize>) -> Result<Schedule, Error> {
let include = distinct(structure, &order)?;
let kept = (0..include.len()).filter(|&k| !include[k]).collect();
Ok(Schedule::build(structure, order, kept))
}The order is COLAMD on the block pattern, one row per factor and one column per block, which faer provides. A marginal keeps some blocks, which are put last by ordering the others and appending them. A replacement eliminates some blocks from the factors joined to them alone. Blocks are grouped into cliques along chains whose separators nest, as the note’s junction tree describes, and each clique is eliminated as one front. Every row of a batch and every iteration of a loop shares one schedule.
Eliminating#
For each clique, the rows of its factors, the new factors its children left and any damping rows are stacked into one front, frontal columns first. The front is reduced by faer’s unpivoted Householder QR, which gives the conditional of the clique’s blocks on its separator and a new factor there, as the lemma of eliminating one block says. The frontal blocks’ linear terms are pushed onto the separator by one forward substitution. The normal equations are never formed.
crates/skoro-elimination/src/eliminate.rs lines 9–20/// `R τ_F + T τ_S = rhs`: what eliminating a clique's frontal blocks leaves, given its separator.
/// `R` is upper triangular with a positive diagonal, its columns the frontal blocks' coordinates
/// in order; `T`'s columns are the separator blocks' in order.
#[derive(Clone, PartialEq, Debug)]
pub struct Conditional {
pub frontals: Vec<usize>,
pub separator: Vec<usize>,
pub r: Matrix,
pub t: Matrix,
/// `d - y`: the reduced right-hand side less the pushes of the frontal blocks' linear terms.
pub rhs: Vec<f64>,
}A diagonal entry of that is small against its column refuses its block as undetermined, at a threshold set by the precision the rows were computed at:
crates/skoro-elimination/src/eliminate.rs lines 336–343/// A frontal diagonal entry at most this, relative to its column's norm before the reduction,
/// is a direction the rows do not determine: `u^{3/4}` of the precision the rows were
/// computed at, between an exact dependence, which leaves a diagonal entry of the order of
/// the rows' rounding `u`, and a determined direction, of order `1 / κ`. About `1.1e-12` for
/// rows computed in double precision and `3.8e-6` for rows computed in single.
fn threshold(&self) -> f64 {
self.roundoff().powf(0.75)
}What an elimination answers is a traversal of its conditionals: the minimizer, , the log-determinant and the integral; the marginal on the kept blocks, by one more factorization with their coordinates reversed, as a lower-triangular whitening with a positive diagonal; and, for a replacement, what is left on the kept blocks, reduced to at most as many rows as they have coordinates with no decision of rank, with the constant of integrating the eliminated blocks out.
Linearizing a query#
A Linearizer is built once for a snapshot, a density query, a target and an assembly:
crates/skoro-linearize/src/linearizer.rs lines 14–22/// Which rows a linearization is assembled from.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Assembly {
/// Each factor's residual: the linearization of the query's negative log-density.
Residual,
/// Each factor's residual and, where the scale is free, its information root's scale rows:
/// the Fisher linearization.
Fisher,
}The query’s free continuous quantities, in the order of its program’s layout, are the blocks. Each term reached from one of them is a factor over the free quantities it involves. A term reached from none is a constant of the query. The linearizer refuses by structure, naming the term or the quantity, what the mathematics cannot linearize: a free discrete quantity, a factor that binds no residual, and, for the residual assembly, a factor whose scale is reached from a free quantity, whose omitted curvature is as large as what its rows keep:
crates/skoro-linearize/src/linearizer.rs lines 131–196for id in terms {
let term = snapshot
.term(id)
.ok_or(skoro_core::Error::NotATerm { id })?;
let mut blocks: Vec<usize> = term
.involves
.iter()
.filter_map(|q| index.get(q).copied())
.collect();
if blocks.is_empty() {
continue;
}
blocks.sort_unstable();
let residual = term
.bound(&roles::RESIDUAL)
.map_err(|_| Error::NoResidual { term: id })?;
let components = snapshot
.space(residual)
.and_then(|space| space.dimension())
.unwrap_or(0);
let mut log_volume = term.bound(&roles::LOG_VOLUME)?;
let fold = folding(snapshot, term, log_volume)?;
if fold.is_some() {
log_volume = None;
}
let mut free_scale = None;
if let Some(scale) = bound_scale(term)? {
let free = snapshot
.reached_from(scale)
.into_iter()
.find(|q| index.contains_key(q));
if let Some(quantity) = free {
match assembly {
Assembly::Residual => {
return Err(Error::ScaleNotFixed { term: id, quantity });
}
Assembly::Fisher => {
let root = term.bound(&roles::INFORMATION_ROOT)?;
let tangent = term.bound(&roles::TANGENT)?;
let (Some(root), Some(tangent)) = (root, tangent) else {
return Err(Error::NoInformationRoot { term: id, quantity });
};
let k = snapshot
.space(scale)
.and_then(|space| space.dimension())
.unwrap_or(0);
free_scale = Some(FreeScale {
scale,
k,
tangent,
root,
});
}
}
}
}
factors.push(Factor {
term: id,
blocks,
residual,
components,
log_volume,
fold,
free_scale,
});
}Every factor’s rows come from one tangent pass of one program, whose targets are the nodes the factors bind. A pass’s frames are dense in their columns, and the identity frame of every free quantity would carry the whole Jacobian, mostly zeros. So the seeds are compressed by colouring the factor structure, the bipartite graph of the note whose nodes are the free quantities and the factors, with an edge between a factor and each quantity it involves: two quantities joined to a common factor get different colours, and each colour owns a few columns. A node a term binds is reached from no quantity outside the term, so a factor’s Jacobian is cut, unmixed, from its quantities’ colours:
crates/skoro-linearize/src/linearizer.rs lines 352–386/// A greedy colouring of the free quantities, in the layout's order: two quantities joined to a
/// common factor in the factor structure have different colours. Each colour owns a range of
/// columns as wide as its widest block; the start of each block's range, and the total width.
fn colouring(dimensions: &[usize], factors: &[Factor]) -> (Vec<usize>, usize) {
let n = dimensions.len();
let mut conflicts: Vec<Vec<usize>> = vec![Vec::new(); n];
for factor in factors {
for &a in &factor.blocks {
for &b in &factor.blocks {
if a != b {
conflicts[a].push(b);
}
}
}
}
let mut colour: Vec<Option<usize>> = vec![None; n];
let mut widths: Vec<usize> = Vec::new();
for k in 0..n {
let taken: Vec<usize> = conflicts[k].iter().filter_map(|&j| colour[j]).collect();
let c = (0..).find(|c| !taken.contains(c)).unwrap_or(0);
colour[k] = Some(c);
if c == widths.len() {
widths.push(0);
}
widths[c] = widths[c].max(dimensions[k]);
}
let mut starts = Vec::with_capacity(widths.len());
let mut width = 0;
for w in &widths {
starts.push(width);
width += w;
}
let columns = colour.iter().map(|c| starts[c.unwrap_or(0)]).collect();
(columns, width)
}A factor’s rows are its residual’s Jacobian, and its right-hand side the negated residual. The linear term is the gradient of the bound log-volumes that are not folded, and it is never formed as the query’s gradient less what the rows account for: that difference would be rounding, which the solve would amplify. The constant makes the linearization agree with the query’s negative log-density at the point.
A factor may have no rows.
The uniform distribution binds a residual of no components, so its factor is a constant alone: it adds nothing to the rows and keeps its in the constant.
A quantity whose only factors have no rows is not determined by them, and its elimination reports it Undetermined.
The rows are read onto the host once, and a point at which any of them is not finite is refused there, naming the first such factor’s term and the row of the batch, rather than carried into the elimination and a step that could only be rejected. Such a point is outside a term’s chart: a rotation given a half-turn from its mean, where the rotations’ chart is cut, or a value that is already non-finite.
crates/skoro-linearize/src/assemble.rs lines 104–124/// `NotFinite` for the first factor, in the factors' order, and the first row at which its
/// residual or its Jacobian, `residuals[f]` as `at` reads it, has an entry that is not
/// finite.
fn finite(&self, residuals: &[(Vec<f64>, Vec<f64>)], rows: usize) -> Result<(), Error> {
for (factor, (values, jacobian)) in self.factors.iter().zip(residuals) {
let d = factor.components;
let width = jacobian.len() / (rows * d).max(1);
for row in 0..rows {
let finite = |data: &[f64]| data.iter().all(|v| v.is_finite());
if !finite(&values[row * d..(row + 1) * d])
|| !finite(&jacobian[row * d * width..(row + 1) * d * width])
{
return Err(Error::NotFinite {
term: factor.term,
row,
});
}
}
}
Ok(())
}Folding a log-volume#
On a curved type, the normal’s log-volume is a function of its tangent alone, and its gradient lies in the span of its own rows. It is carried by the right-hand side, with , rather than by the linear term. A model of normals on the Euclidean and curved types then has no linear term at all. Folding is decided by the term’s roles and its scored quantity’s type, never by a number:
crates/skoro-linearize/src/linearizer.rs lines 320–350/// The fold of a term's log-volume, when it binds the tangent, the log-volume and the information
/// root, and scores a quantity of a space whose chart's log-volume does not read its point: then
/// its residual is `W s` and its log-volume `λ(s)`, a function of the tangent alone. The scale is
/// held by every assembly that reaches here, fixed by the residual linearization's refusal or held
/// at the point by Fisher's.
fn folding(
snapshot: &Snapshot,
term: &Term,
log_volume: Option<QDyn>,
) -> Result<Option<Fold>, Error> {
let (Some(_), Some(tangent), Some(root), Some(scored)) = (
log_volume,
term.bound(&roles::TANGENT)?,
term.bound(&roles::INFORMATION_ROOT)?,
term.scores,
) else {
return Ok(None);
};
let Some(space) = snapshot.space(scored).cloned() else {
return Ok(None);
};
if space.volume_reads_point() != Ok(false) {
return Ok(None);
}
Ok(Some(Fold {
tangent,
mean: term.bound(&roles::MEAN)?,
root,
space,
}))
}Space::volume_reads_point reads, from the type’s declared log-volume, whether it depends on the base point; on a positive type it does, and the log-volume stays in the linear term. is computed on the host, from the space’s own log-volume and the whitening read off the information root:
crates/skoro-linearize/src/assemble.rs lines 252–319/// Each folded factor's `ĉ = W⁻ᵀ ∇λ_μ(s)`, row by row: the gradient of its space's chart
/// log-volume at `(μ̂, ŝ)`, for every folded factor of the space and every row at once, and
/// `W` the top-left block of the information root's value.
pub(crate) fn folds(&self, pass: &Pass) -> Result<Vec<Option<Vec<f64>>>, Error> {
let mut folds: Vec<Option<Vec<f64>>> = vec![None; self.factors.len()];
for (space, program) in &self.volumes {
let members: Vec<usize> = (0..self.factors.len())
.filter(|&f| {
self.factors[f]
.fold
.as_ref()
.is_some_and(|g| g.space == *space)
})
.collect();
let (Some(storage), Some(d)) = (Some(space.storage()), space.dimension()) else {
continue;
};
let (mut means, mut tangents) = (Vec::new(), Vec::new());
let mut roots = Vec::new();
for &f in &members {
let Some(fold) = &self.factors[f].fold else {
continue;
};
means.extend(host(&pass.values, fold.mean)?);
tangents.extend(host(&pass.values, fold.tangent)?);
roots.push(host(&pass.values, fold.root)?);
}
let n = members.len() * pass.rows;
let host_target = Target::host();
let free = program.free();
let (Some(point), Some(tangent)) = (free.first(), free.get(1)) else {
continue;
};
let at = Values::new()
.with(
point.node,
Value::Continuous(Points::from_host(&means, n, storage, &host_target)),
)
.with(
tangent.node,
Value::Continuous(Points::from_host(&tangents, n, d, &host_target)),
);
let (_, gradients) = program.gradient(&at)?;
let gradient = frame(&gradients, tangent.node)?;
for (m, &f) in members.iter().enumerate() {
let root = &roots[m];
let size = root.len() / pass.rows.max(1);
// The root's rows: the residual's `d`, then the scale's `d(d + 1)/2`.
let height = d + d * (d + 1) / 2;
let mut c = Vec::with_capacity(pass.rows * d);
for row in 0..pass.rows {
let entries = &root[row * size..(row + 1) * size];
// `C` is stored column by column: entry (i, j) at `j × height + i`.
let w = |i: usize, j: usize| entries[j * height + i];
let g = &gradient[(m * pass.rows + row) * d..(m * pass.rows + row + 1) * d];
// `Wᵀ ĉ = g`, `W` lower triangular: back substitution.
let mut x = vec![0.0; d];
for i in (0..d).rev() {
let rest: f64 = (i + 1..d).map(|j| w(j, i) * x[j]).sum();
x[i] = (g[i] - rest) / w(i, i);
}
c.extend(x);
}
folds[f] = Some(c);
}
}
Ok(folds)
}The Fisher rows of a free scale#
The residual assembly refuses a free scale. Assembly::Fisher takes it, replacing the Hessian in the scale by the expected information through the root the normal binds.
A factor with a free scale gives above the root’s scale rows composed with the scale’s Jacobian, and the scale residual on the right, so that the scale’s score is carried by the rows too:
crates/skoro-linearize/src/assemble.rs lines 424–473/// The Fisher rows of a free scale at batch row `row`: `J^μ = W D s` above
/// `J^θ = C_θ D θ`, and the scale residual `u`, laid out as the root's rows: the `d` pairs
/// `(a, a)`, `((r_a)² - 1)/√2`, then the pairs `(a, b)`, `a > b`, `r_a r_b`, column `b` after
/// column `b - 1`.
fn scale_rows(
&self,
factor: &crate::linearizer::Factor,
scale: &crate::linearizer::FreeScale,
reads: &ScaleReads,
row: usize,
r_hat: &[f64],
) -> (Matrix, Vec<f64>) {
let d = factor.components;
let p = d * (d + 1) / 2;
let k = scale.k;
let height = d + p;
let size = height * (2 * d + k);
let root = &reads.root[row * size..(row + 1) * size];
// `C` is stored column by column.
let c = |i: usize, j: usize| root[j * height + i];
let ds = self.cut(&reads.tangent, row, d, &factor.blocks);
let dtheta = self.cut(&reads.scale, row, k, &factor.blocks);
let width = ds.columns();
let mut data = Vec::with_capacity(height * width);
for i in 0..d {
for col in 0..width {
data.push((0..d).map(|j| c(i, j) * ds.get(j, col)).sum());
}
}
for i in 0..p {
for col in 0..width {
data.push(
(0..k)
.map(|j| c(d + i, 2 * d + j) * dtheta.get(j, col))
.sum(),
);
}
}
let mut u: Vec<f64> = r_hat
.iter()
.map(|r| (r * r - 1.0) * std::f64::consts::FRAC_1_SQRT_2)
.collect();
for b in 0..d {
for a in b + 1..d {
u.push(r_hat[a] * r_hat[b]);
}
}
let rows = Matrix::new(height, width, data).unwrap_or_else(|| Matrix::zeros(height, width));
(rows, u)
}With every scale fixed the two assemblies are the same, row for row, and one schedule serves both.
Steps, marginals and the Laplace approximation#
A Linearized holds one problem per row of the batch.
Eliminated along a schedule, it gives a Solved, whose minimizer is a step that the layout retracts onto the quantities, and whose refusals of a block name its quantity:
crates/skoro-linearize/src/solved.rs lines 38–63impl Linearized {
/// Eliminates every row along `schedule`, which must be of the linearizer's structure, with
/// the damping rows appended if given; refuses a free quantity the rows do not determine
/// (`Undetermined`).
pub fn eliminate(
&self,
schedule: &Schedule,
damping: Option<&Damping>,
) -> Result<Solved, Error> {
let eliminations = self
.problems
.iter()
.map(|problem| {
problem
.eliminate(schedule, damping)
.map_err(|e| undetermined(e, &self.layout))
})
.collect::<Result<_, Error>>()?;
Ok(Solved {
eliminations,
assembly: self.assembly,
layout: self.layout.clone(),
curved: self.curved.clone(),
})
}
}A Laplace approximation is these pieces on the chart linearization at a mode, which subtracts the log-volume of the charts of the quantities integrated over, so that its Gaussian is centred where the chart is: on a log-normal quantity, at its median. Its marginals name the quantities they are over, and which of them are curved:
crates/skoro-linearize/src/solved.rs lines 28–36/// A marginal of the linearization, over named quantities.
#[derive(Clone, Debug)]
pub struct QuantityMarginal {
/// The kept quantities, in the order of the marginal's blocks.
pub quantities: Vec<NodeId>,
/// Those of them of a curved type, whose covariance is reported with an error of order `σ²`.
pub curved: Vec<NodeId>,
pub marginal: Marginal,
}A draw takes one key per row, standard normals by the normal’s quantile, and :
crates/skoro-linearize/src/solved.rs lines 137–157/// A draw per row, `τ* + R⁻¹ z` with `z` standard normal from `key`, one key per row by
/// `Key::split`, retracted onto the quantities at `at` (`NotAnIntegral` of a Fisher
/// linearization). On a curved quantity its spread errs as the covariance does.
pub fn draw(&self, at: &Values, key: &Key, target: &Target) -> Result<Values, Error> {
self.integral()?;
let d = self.layout.dimension();
let keys = key.split(self.eliminations.len());
let mut data = Vec::with_capacity(self.eliminations.len() * d);
for (elimination, key) in self.eliminations.iter().zip(&keys) {
let z: Vec<f64> = key
.uniforms(d)
.into_iter()
.map(skoro_normal::quantile)
.collect();
let spread = elimination.solve(&z)?;
let centre = elimination.minimizer()?;
data.extend(centre.iter().zip(&spread).map(|(c, s)| c + s));
}
let tangent = Points::from_host(&data, self.eliminations.len(), d, target);
Ok(self.layout.retract(at, &tangent, target)?)
}The Fisher linearization gives steps and covariances, and refuses an evidence, a draw and a chart linearization: those approximate an integral of the density, whose curvature in a free scale is not the expected information.
Minimizing: the Levenberg–Marquardt method#
A step from one linearization is Gauss–Newton’s, and far from the mode it can overshoot.
A LevenbergMarquardt runs the damped method on every row of a batch at once, each row with its own damping, its own point and its own stop, sharing with the others only the passes that linearize them all:
crates/skoro-linearize/src/minimize.rs lines 11–37/// The Levenberg–Marquardt method of the examples' mathematics: Marquardt's diagonal, Nielsen's
/// schedule, and a stop on the promised decrease, run on each row of a batch separately.
#[derive(Clone, Debug)]
pub struct LevenbergMarquardt {
/// `λ₀`: 1e-3.
pub initial_damping: f64,
/// `δ`, the floor of `D`: 1e-12.
pub floor: f64,
/// `ε`, in nats: 1e-9. Must stay well above `u |f|` at the query's precision.
pub tolerance: f64,
/// `λ_max`: 1e10. A row whose damping passes it has not converged.
pub max_damping: f64,
/// The bound on iterations, accepted and rejected alike: 100.
pub max_iterations: usize,
}
impl Default for LevenbergMarquardt {
fn default() -> LevenbergMarquardt {
LevenbergMarquardt {
initial_damping: 1e-3,
floor: 1e-12,
tolerance: 1e-9,
max_damping: 1e10,
max_iterations: 100,
}
}
}Each iteration damps each row by Marquardt’s diagonal (2), the squared norm of each coordinate’s column of its rows, so that the damping is invariant to the units of the coordinates.
It eliminates the row with its own Damping, retracts every row’s step in one pass, and reads at the trial points by Linearizer::objective, one forward pass of the query’s density program.
The gain (4), the decrease obtained over the decrease promised, decides each row alone: a step that decreased is taken, and the damping follows Nielsen’s schedule (5):
crates/skoro-linearize/src/minimize.rs lines 167–185 // `f` before the step is the problem's value at zero, by its constant.
let before = problems[r].value(&zero);
let gain = (before - after[r]) / promised[r];
let accept = gain > 0.0;
row.history.push(Iterate {
objective: before,
damping: row.lambda,
promised: promised[r],
gain,
accepted: accept,
});
// Taken if it decreases f, converged or not.
accepted[r] = accept;
if promised[r] <= self.tolerance {
row.done = Some(Status::Converged);
continue;
}
nielsen(&mut row.lambda, &mut row.beta, gain);
}A row that does not converge is not an error.
Every row ends with a Status and the history of its iterations, and the caller decides what a row that ran out of damping or iterations means:
crates/skoro-linearize/src/minimize.rs lines 39–48/// How a row's minimization ended.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Status {
/// A step, accepted or not, promised at most `tolerance`.
Converged,
/// `λ` passed `max_damping`: no step decreased `f`.
DampingExceeded,
/// `max_iterations` passed first.
IterationsExceeded,
}The damped promise bounds the distance to the mode only while the damping is small, so stationarity is checked apart from the stop, by decrement: the undamped promise , which is zero exactly where the query’s gradient is.
crates/skoro-linearize/src/minimize.rs lines 195–219/// `½|J τ₀|²` per row at `at`: the Gauss–Newton decrement, with `τ₀` the undamped step, zero
/// exactly where the query's chart gradient is, the rows being of full rank.
pub fn decrement(
linearizer: &Linearizer,
schedule: &Schedule,
at: &Values,
) -> Result<Vec<f64>, Error> {
let linearized = linearizer.at(at)?;
let layout = linearizer.layout();
let zero = Damping {
lambda: 0.0,
diagonal: vec![0.0; layout.dimension()],
};
linearized
.problems()
.iter()
.map(|problem| {
let step = problem
.eliminate(schedule, None)
.and_then(|e| e.minimizer())
.map_err(|e| undetermined(e, layout))?;
Ok(problem.promised(&step, &zero))
})
.collect()
}A retirement’s replacement#
A retirement removes some quantities and needs a replacement for the terms joined to them, the integral of those terms over the quantities it integrates.
A Replacing linearizes the query of those terms alone, free in the quantities to integrate and in the blanket quantities to keep, with the retirement’s own observed values:
crates/skoro-linearize/src/replacing.rs lines 120–158/// The replacement linearized at `at`, which holds `p̂_E` and the anchors `p̂_B`: in the chart
/// of `E_F` alone, `E_F` eliminated by integration, and what is left reduced to
/// `min(m', D)` rows with no decision of rank. A retired quantity its terms do not determine
/// is `RetiredUndetermined`. On a curved quantity of the blanket its precision errs by a
/// relative amount of order `σ²`, the noise's variance in its chart, and more over a sequence
/// of retirements that measure nothing.
pub fn at(&self, at: &Values) -> Result<LinearizedReplacement, Error> {
let linearized = self.linearizer.at_in_chart(at, &self.integrated)?;
let layout = self.linearizer.layout();
let mut reduced = Vec::with_capacity(linearized.problems().len());
for problem in linearized.problems() {
let elimination = problem
.eliminate(&self.schedule, None)
.map_err(|e| match e {
skoro_elimination::Error::Undetermined { block } => {
Error::RetiredUndetermined {
quantity: layout.quantities()[block],
}
}
other => Error::Elimination(other),
})?;
reduced.push(elimination.reduced());
}
let rows = linearized.problems().len();
let mut blocks = Vec::new();
for (q, space) in &self.kept {
let data = host(at, *q)?;
let anchor = HostValue::new(
(rows > 1).then_some(rows),
space.storage(),
HostData::Continuous(data),
)
.ok_or(Error::Core(skoro_core::Error::ValueShape {
space: space.clone(),
}))?;
blocks.push((*q, space.clone(), anchor));
}
Ok(LinearizedReplacement { blocks, reduced })
}The replacement is the improper factor of the normal, in the kept quantities’ stacked tangent at the linearization point, built in the retirement’s scope:
crates/skoro-linearize/src/replacing.rs lines 186–228/// The improper factor as the core's `Replacement`, its roles bound: to be called inside
/// `Retirement::replace`'s body. The blocks are stacked in the order of `A`'s columns, which
/// both come from the layout, and `A` is stored column by column, as a `MatrixDyn` is.
#[track_caller]
pub fn build(&self) -> Replacement {
let constants: Vec<f64> = self.reduced.iter().map(|r| r.constant).collect();
if self.blocks.is_empty() {
let c = match constants.as_slice() {
[c] => constant(Real, *c),
_ => constant(Real, Rows(constants.clone())),
};
return Replacement {
log_density: c + 0.0,
proposals: Vec::new(),
bindings: Vec::new(),
};
}
let stacked = self
.blocks
.iter()
.fold(Stacked::new(), |stacked, (q, space, anchor)| {
stacked.block_in(*q, space, anchor.clone())
});
let rows = self.rows();
let a: Vec<Vec<f64>> = self.reduced.iter().map(|r| r.a.by_columns()).collect();
let b: Vec<Vec<f64>> = self.reduced.iter().map(|r| r.b.clone()).collect();
let improper = if self.reduced.len() == 1 {
stacked.improper(rows, a[0].as_slice(), b[0].as_slice(), constants[0])
} else {
let a: Vec<&[f64]> = a.iter().map(Vec::as_slice).collect();
let b: Vec<&[f64]> = b.iter().map(Vec::as_slice).collect();
stacked.improper(rows, Rows(a), Rows(b), Rows(constants.clone()))
};
let linear: Option<Vec<Vec<f64>>> = self.reduced.iter().map(|r| r.linear.clone()).collect();
let improper = match linear {
Some(eta) if self.reduced.len() == 1 => improper.linear(eta[0].as_slice()),
Some(eta) => {
improper.linear(Rows(eta.iter().map(Vec::as_slice).collect::<Vec<&[f64]>>()))
}
None => improper,
};
improper.replacement()
}Its number of rows, and whether it has a linear term, are fixed by the retired terms and their types, so every row of a batch has a replacement of one shape. For linear-Gaussian terms it is exact, and retiring one state at a time from a chain is the Kalman filter. Otherwise, linearized at the retired terms’ mode it is an iterated extended Kalman filter’s step. Where the retired terms do not determine the blanket, the replacement keeps what they say, and replacements over the same quantity add until they determine it.
How this came to be
The development behind this page, newest first:
- Least squares, motivated from MAP estimation and trust regions Done This entry reordered the mathematics' part on least squares and Gaussian approximations so that it begins with the estimate sought and ends with the linear algebra that computes it. Five notes are…
- The uniform distribution on compact types, and broad scales of a normal on a curved type Done A broad normal on a rotation is not a weak prior. Under the Cayley chart a tangent of length is a turn by , and once the standard deviation of the normal passes one radian its mean…
- The Mathematics section, read start to finish Done The Mathematics section was a collection of notes, one idea to a note, linked by what each builds on, while most of the mathematics the pages relied on sat in the archive's frozen documents, argued in…
- Observed quaternions of arbitrary sign on outside data Done The rotations, the rigid motions and the extended poses were declared as the unit quaternions and their products, with the stereographic chart, which tells from : an observed quaternion had to…
- Free the constants a retirement leaves with no consumer Done A retirement removed the retired quantities and every node computed from them, but never a constant, or a value folded from constants, since those are computed from no quantity: the scales, the…
- Examples that run Done This entry gave skoro two examples that run, in the umbrella crate, each a cargo run --example target that CI runs and that fails when a check of its mathematics fails. pose_graph draws a hundred…
- Linearization and elimination Done This entry brought back the two pieces every least-squares method rests on, as two crates. skoro-elimination is the note on elimination in square-root form as code: factored problems over blocks of…