Terms and the probabilistic graph
A model's density is a sum of terms, each a log-density that scores one quantity or none; the terms and quantities together make the probabilistic graph inference reads, and a retirement removes some quantities, replaces their terms, and frees what it leaves needed by nothing.
A model’s quantities say what is uncertain; its terms say how. A term is a log-density, built from the model’s quantities by operations like any other value, and the model’s density is the sum of its terms. This page describes terms, the probabilistic graph they make with the quantities, and what a snapshot can say about it.
A term#
crates/skoro-core/src/term.rs lines 16–27/// A term: a log-density, the quantity it scores if any, and the quantities it involves.
#[derive(Clone, Debug)]
pub struct Term {
/// A mapped node of space `Real`.
pub log_density: NodeId,
/// `s_t`: the quantity the term scores, `None` for a likelihood factor.
pub scores: Option<NodeId>,
/// `V_t`, sorted: the quantities the log-density is reached from, with the one it scores.
pub involves: Box<[NodeId]>,
pub sampler: Option<Sampler>,
pub(crate) bindings: Vec<(&'static str, NodeId)>,
}A term is added in one of two ways:
crates/skoro-core/src/term.rs lines 328–351/// Adds the term `log_density` that scores `scored`: refusing a log-density that is not a mapped
/// `Real` (`NotALogDensity`), a quantity already scored (`AlreadyScored`), a quantity whose space
/// has no reference measure (`NoVolume`), and a term conditioned on a quantity made after the one
/// it scores (`ConditionedOnLater`).
#[track_caller]
pub fn score<T: Typed>(scored: Q<T>, log_density: Q<Real>) -> TermHandle {
let location = Location::caller();
TermHandle {
id: scope::build(location, |draft, _| {
draft.add_term(Some(scored.untyped()), log_density.untyped())
}),
}
}
/// Adds the likelihood factor `log_density`, which scores nothing.
#[track_caller]
pub fn factor(log_density: Q<Real>) -> TermHandle {
let location = Location::caller();
TermHandle {
id: scope::build(location, |draft, _| {
draft.add_term(None, log_density.untyped())
}),
}
}score adds the term of the distribution a quantity was drawn from: its density, as a function of the quantity it scores and the quantities it is conditioned on. factor adds a likelihood factor, which scores nothing: the likelihood of data that is not a quantity of the model.
Either way, the log-density must be computed by an operation and be a Real.
A term that scores a quantity is a density against the reference measure of the quantity’s space, so a quantity whose space has none cannot be scored, and is a parameter, which likelihood factors may still be conditioned on.
A distribution that scores the quantities drawn from it, such as the normal, implements Distribution, whose score adds its term at a quantity, with whatever sampler and roles the distribution gives it:
crates/skoro-core/src/term.rs lines 313–326/// What scores a quantity: a distribution, whose term draws the quantity it scores.
pub trait Distribution {
/// Adds the term that scores `x`, with its sampler and roles, in the open scope, recording a
/// refusal at the caller's line.
#[track_caller]
fn score(&self, x: QDyn) -> TermHandle;
}
impl<D: Distribution + ?Sized> Distribution for &D {
#[track_caller]
fn score(&self, x: QDyn) -> TermHandle {
(**self).score(x)
}
}Most quantities are made and scored at once, so the scope has a function that does both: sample makes a quantity at an address, scores it by the distribution, and returns it, and sample_in does the same for a space given as a value.
What they build is exactly what quantity and the distribution’s score build, and a refusal by either is recorded at the line that called them:
crates/skoro-core/src/scope.rs lines 349–373/// A quantity of `marker`'s space at `address`, scored by `distribution`: what `quantity` and the
/// distribution's `score` build, with a refusal by either recorded at the caller's line.
#[track_caller]
pub fn sample<T: Declares>(
address: impl Into<Address>,
marker: T,
distribution: impl Distribution,
) -> Q<T> {
let x = quantity(address, marker);
distribution.score(x.untyped());
x
}
/// A quantity of `space` at `address`, scored by `distribution`: what `quantity_in` and the
/// distribution's `score` build, with a refusal by either recorded at the caller's line.
#[track_caller]
pub fn sample_in(
address: impl Into<Address>,
space: Space,
distribution: impl Distribution,
) -> QDyn {
let x = quantity_in(address, space);
distribution.score(x);
x
}Which quantities a term involves is never declared. It is read off the compilation graph: the quantities among the roots its log-density is computed from. Two rules keep the model generative. A quantity is scored by at most one term, the distribution it was drawn from. And a term is conditioned only on quantities made before the one it scores, so the order in which quantities were made is an ancestral order, in which each comes after everything its distribution depends on. A quantity no term scores is a parameter, such as a sensor reading the model is driven by.
The same reading is open for any node: Snapshot::reached_from gives the quantities a node is reached from, which for a term’s log-density is what it involves, and for a node it binds, such as a normal’s scale, says whether the node moves with the free quantities of a query.
crates/skoro-core/src/model.rs lines 353–358/// The quantities `id` is reached from in the compilation graph, walking back through mapped
/// nodes and stopping at nodes fixed in the model, sorted: what `Term::involves` holds for a
/// log-density.
pub fn reached_from(&self, id: impl Into<NodeId>) -> Vec<NodeId> {
crate::term::roots(&self.0, id.into())
}An example#
A vehicle at and then measures a landmark once from each position, as and . Its motion is driven by an inertial reading , and a second motion model is a likelihood factor over , and a scale :
crates/skoro-core/tests/queries.rs lines 31–57fn example() -> Example {
let mut writer = Writer::new();
let (x0, x1, m, z0, z1, zeta, sigma, t) = writer
.build(|| {
let half = constant(Real, 0.5);
let x0 = quantity("tick/0/x", Vector::<2>);
let t1 = score(x0, -(x0 * x0).sum() * half);
let m = quantity("landmark", Vector::<2>);
let t2 = score(m, -(m * m).sum() * half);
let zeta = quantity("tick/1/imu", Vector::<2>);
let sigma = quantity("sigma", Positive::<1>);
let x1 = quantity("tick/1/x", Vector::<2>);
let step = x1 - x0 - zeta;
let t3 = score(x1, -(step * step).sum());
let z0 = quantity("tick/0/z", Vector::<2>);
let r0 = z0 - (m - x0);
let t4 = score(z0, -(r0 * r0).sum());
let z1 = quantity("tick/1/z", Vector::<2>);
let r1 = z1 - (m - x1);
let t5 = score(z1, -(r1 * r1).sum());
let r = x1 - x0;
let inverse = (sigma * sigma).recip().as_real().sum();
let t6 = factor(-(r * r).sum() * half * inverse - 2.0 * sigma.log().sum());
let t7 = factor(-sigma.log().sum());
(x0, x1, m, z0, z1, zeta, sigma, [t1, t2, t3, t4, t5, t6, t7])
})
.unwrap();Five terms score the five quantities , , , and ; and are parameters; t6 and t7 are likelihood factors, the second an improper prior on .
The probabilistic graph#
The quantities and terms make the model’s probabilistic graph. Its nodes are the quantities and the terms; it has an edge from each quantity a term is conditioned on to the term, and from each term to the quantity it scores. Every edge joins a quantity and a term, and the graph is acyclic, by the rule above. For the example:
- Quantity
- Parameter
- Term scoring a quantity
- Likelihood factor
- conditions a term
- scores a quantity
Inference reads this graph rather than being told about it. A snapshot answers the questions an algorithm asks of it, among them the Markov blanket of some quantities, which is what a sampler or a sliding window needs: the other quantities the same terms involve, so that the quantities’ conditional density, given everything else, is the sum of the terms they are joined to, up to a constant. For the first tick of the example:
- Quantity
- Parameter
- Term scoring a quantity
- Likelihood factor
- Quantity asked about
- Term joined to them
- Likelihood factor joined to them
- Quantity in the blanket
- Parameter in the blanket
- conditions a term
- scores a quantity
crates/skoro-core/src/model.rs lines 274–317/// The term that scores `q`, if one does.
pub fn scored_by(&self, q: impl Into<NodeId>) -> Option<&Term> {
let id = self.0.scoring.get(&q.into())?;
self.term(*id)
}
/// The terms `q` is joined to, in the order they were added.
pub fn terms_of(&self, q: impl Into<NodeId>) -> Vec<&Term> {
let mut ids: Vec<NodeId> = self
.0
.joined
.get(&q.into())
.map(|terms| terms.iter().copied().collect())
.unwrap_or_default();
ids.sort_unstable();
ids.into_iter().filter_map(|id| self.term(id)).collect()
}
/// Whether `q` is a quantity no term scores.
pub fn is_parameter(&self, q: impl Into<NodeId>) -> bool {
let id = q.into();
self.node(id).is_some_and(Node::is_quantity) && !self.0.scoring.contains_key(&id)
}
/// The proposal attached to the parameter `q`.
pub fn proposal(&self, q: impl Into<NodeId>) -> Option<&Proposal> {
self.0.proposals.get(&q.into()).map(Arc::as_ref)
}
/// The Markov blanket of `quantities`: the other quantities joined to the terms they are
/// joined to, in ancestral order.
pub fn blanket<Q: Into<NodeId>>(&self, quantities: impl IntoIterator<Item = Q>) -> Vec<NodeId> {
let inside: std::collections::HashSet<NodeId> =
quantities.into_iter().map(Into::into).collect();
let mut blanket: Vec<NodeId> = inside
.iter()
.flat_map(|q| self.terms_of(*q))
.flat_map(|term| term.involves.iter().copied())
.filter(|q| !inside.contains(q))
.collect();
blanket.sort_unstable();
blanket.dedup();
blanket
}Every step
- A sliding window that retires the first tick asks for the blanket of and .
terms_ofgives the terms a quantity is joined to: the one that scores it, those conditioned on it, and the factors that involve it. is joined to , , and , and to .- Each term's
involveslists the quantities its log-density is computed from. Those not asked about make the blanket: , , and . - The other terms involve neither nor . Given everything else, their conditional density is up to a constant, which reads the blanket alone.
blanketreturns it in ancestral order.
The mathematics of all this is in the note on generative models. skoro is built on that note’s view of a model: not a function to be evaluated, but a probability space built forward, quantity by quantity, which the library lets its users work with in every way the measure theory allows. It states a model as the note’s sum of logarithms, one term for each kernel, likelihood factor and score. Of the graphs the note draws of a model, skoro keeps the probabilistic graph above, of quantities and terms, and adds the compilation graph of the values each term is computed from, over which derivatives are taken. The note’s dependence graph and factor graph are both read off the probabilistic graph: contracting each term into edges from the quantities it is conditioned on to the quantity it scores gives the first, and forgetting the directions gives the second, on which the Markov blanket is read.
A term may also carry a sampler, which draws the quantity it scores, and bindings, which mark its parts by role (a residual, a whitening factor) for the algorithms that read them. A parameter may carry a proposal, which draws it when the model is generated. What a generated point weighs, given the samplers and proposals it was drawn from, is the subject of the note on importance weights.
Retirement#
A model that runs indefinitely must forget: once some quantities stop mattering, they are removed, and what their terms said about the rest is kept in a smaller form. That is a retirement. The writer reads one for the quantities at some addresses, named one by one or as the namespaces they lie under, with the values of those it fixes rather than integrates out:
crates/skoro-core/src/retire.rs lines 113–122/// Reads the retirement of the quantities at `addresses`, resolved on the latest snapshot,
/// with `observed` the values of those it fixes rather than integrates; refuses an exact
/// address with no quantity (`UnknownAddress`), an observed quantity outside them
/// (`ObservedNotRetired`), and a quantity to integrate whose space has no reference measure
/// (`NoVolume`). Changes nothing.
pub fn retire(
&mut self,
addresses: Addresses,
observed: Observations,
) -> Result<Retirement<'_>, Error> {Reading changes nothing. The plan says what the change will be: the retired quantities, the terms joined to them, and their Markov blanket, the quantities those terms involve beyond the retired ones:
crates/skoro-core/src/retire.rs lines 69–84/// What a retirement reads before anything changes.
#[derive(Clone, Debug)]
pub struct Plan {
/// `E`: the quantities at the retirement's addresses, in ancestral order.
pub retired: Vec<QDyn>,
/// The values of `E_O`.
pub observed: Observations,
/// `E_F`: the quantities of `E` the replacement integrates out.
pub integrated: Vec<QDyn>,
/// `𝒯_E`: the terms joined to a quantity of `E`, in the order they were added.
pub terms: Vec<Arc<Term>>,
/// `B`: the other quantities joined to those terms, with their spaces and addresses.
pub blanket: Vec<(QDyn, Space, Address)>,
/// Parameters outside `E` whose proposal reads a quantity of `E`, and so loses it.
pub unproposed: Vec<QDyn>,
}The caller builds a replacement for those terms, a likelihood factor over the blanket that stands in for their integral over what is retired. Its log-density is built in a scope the retirement opens, from the plan, by the same functions as any term, and the retirement applies the whole change in one snapshot:
crates/skoro-core/src/retire.rs lines 223–242/// Builds the replacement in a scope, checks it, and applies the change: the replacement
/// must be reached from blanket quantities alone (`ReplacementOutsideBlanket`), and each
/// proposal be for a blanket quantity the retirement leaves unscored or a parameter of
/// `unproposed` (`ProposalNotNeeded`), reading no retired quantity (`ProposalReadsRetired`),
/// and each binding be of a node reached from no quantity outside the replacement's
/// (`BindingOutsideTerm`). Then `E`, the terms of `𝒯_E`, the proposals of `E` and of
/// `unproposed`, and every mapped node reached from `E` are removed, the replacement is added
/// as a likelihood factor with its bindings and the proposals attached, every node the change
/// leaves needed by nothing is freed (one that is no quantity, has no consumer, and is no
/// term's log-density, named by no binding, sampler or proposal, and not pinned), and one
/// snapshot is published; the factor's handle is given back. Freeing visits only what the
/// change touched: the inputs of removed nodes, what the dropped terms and proposals named,
/// and the nodes `body` made, so a node the retirement never touched stays. A failure at any point leaves the model as
/// it was. A retirement of nothing changes nothing, does not call `body`, and gives back no
/// factor.
#[track_caller]
pub fn replace(
self,
body: impl FnOnce(&Plan) -> Replacement,
) -> Result<Option<TermHandle>, Failure> {The normal builds a replacement in the blanket’s stacked tangent, and linearization computes one from the retired terms themselves.
What a retirement frees#
Removing the retired quantities removes every value computed from them, but a value computed from no quantity is not reached that way: a constant, or a value folded from constants. The scales of a retired term’s normal, its mean’s anchor, and an earlier replacement’s matrix and right-hand side are all such values, and once their terms are gone nothing reads them. So a retirement also frees every node it leaves needed by nothing: a node that is no quantity, has no consumer in the compilation graph, and is held by nothing outside its edges, which is to say it is no term’s log-density and is named by no binding, no sampler and no proposal. Freeing a node may leave its inputs with no consumer, and they are freed in turn.
Freeing is local. It visits only what the change touched: the inputs of the nodes removed, the nodes the dropped terms and proposals named, and the nodes the replacement’s scope made. A value that nothing has read since it was built, and that the retirement never touched, stays. It changes no value of the model: every term, sampler and proposal left reads only nodes that are left, so the model’s density, and every query of it, is what it would have been with the freed nodes kept. The mathematics, and the proof of both, are in the entry that added it.
Freeing is what keeps a model that retires as it grows to a bounded size: its nodes are those its current quantities, terms, samplers, proposals and pins need, with at most the values that no retirement has touched since they were built.
A window that keeps its last few ticks holds a number of nodes that stops growing once it is full, as the sliding window checks. Snapshot::nodes lists a snapshot’s nodes, and Snapshot::len counts them.
Pins#
A handle names a node and is bound to no writer, so the model cannot know which handles a user still holds, and holding one does not keep its node.
A handle to a freed node fails as any handle the model does not hold does, with UnknownNode, and never names another node, since identifiers are never reused.
Most nodes need no keeping, but some do: a constant made when the model is configured, such as a measurement noise that every tick reads, may lose its last consumer at a retirement that comes before the next tick is added.
A node the user wants kept, whether or not anything uses it, is pinned:
crates/skoro-core/src/scope.rs lines 455–487/// Keeps `node` through every retirement that does not remove what it is reached from, whether or
/// not anything uses it (`UnknownNode`, `FailedOperand`, `OutsideScope`, `NotInAModel`). Pinning
/// a pinned node changes nothing. Gives back the same handle, failed if the pin was refused.
#[track_caller]
pub fn pin<H: Handle>(node: H) -> H {
let location = Location::caller();
let q: QDyn = node.into();
node.with_id(build(location, |draft, _| {
draft.spaces(&[q])?;
if !draft.in_model {
return Err(Error::NotInAModel);
}
draft.model.pinned.insert_mut(q.id());
Ok(q.id())
}))
}
/// Releases a pin: the next retirement frees the node if nothing else needs it (`UnknownNode`,
/// `FailedOperand`, `OutsideScope`, `NotInAModel`). Unpinning a node that is not pinned changes
/// nothing. Gives back the same handle, failed if the release was refused.
#[track_caller]
pub fn unpin<H: Handle>(node: H) -> H {
let location = Location::caller();
let q: QDyn = node.into();
node.with_id(build(location, |draft, _| {
draft.spaces(&[q])?;
if !draft.in_model {
return Err(Error::NotInAModel);
}
draft.model.pinned.remove_mut(&q.id());
Ok(q.id())
}))
}A pin keeps a node from being freed, not from being retired: a pinned value computed from a retired quantity is removed with it.
A released pin returns its node to the rule, and the next retirement frees it if nothing else needs it, even a retirement that touches nothing near it.
Pins are part of the model, so a snapshot carries them, Snapshot::is_pinned reads them, and a branch forked from a snapshot changes its own.
In the retirement tests, a first tick whose measurement alone reads a noise constant:
crates/skoro/tests/retirement.rs lines 1587–1611fn noisy(pinned: bool) -> Noisy {
let mut writer = Writer::new();
let (z0, x1, noise) = writer
.build(|| {
let noise = constant(Real, 0.1);
if pinned {
pin(noise);
}
let x0 = quantity("tick/0/x", Real);
score(x0, log_density(x0, constant(Real, A), S));
let z0 = quantity("tick/0/z", Real);
score(z0, log_density(z0, x0 + noise, R));
let x1 = quantity("tick/1/x", Real);
score(x1, log_density(x1, x0, QN));
(z0, x1, noise)
})
.unwrap();
Noisy {
writer,
z0,
x1,
noise,
}
}
keeps the noise through the retirement of that tick when it is pinned, and a second tick reads it; unpinned, the same retirement frees it, and the second tick’s build fails:
crates/skoro/tests/retirement.rs lines 1622–1640#[test]
fn pinned_constant_survives_a_retirement_that_leaves_it_unused() {
// Retiring before adding: the noise has no consumer once the first tick is gone.
let mut kept = noisy(true);
retire_first_tick(&mut kept.writer, kept.z0, kept.x1);
assert!(kept.writer.snapshot().node(kept.noise).is_some());
measure_second_tick(&mut kept.writer, kept.x1, kept.noise).unwrap();
assert_closed(&kept.writer.snapshot(), []);
let mut freed = noisy(false);
retire_first_tick(&mut freed.writer, freed.z0, freed.x1);
assert!(freed.writer.snapshot().node(freed.noise).is_none());
assert_eq!(
measure_second_tick(&mut freed.writer, freed.x1, freed.noise),
Err(Error::UnknownNode {
id: freed.noise.id()
})
);
}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…
- Smooth maps before retractions Done The Mathematics section used to define a retraction by its derivative at the origin before it said what a derivative on a manifold is. This entry reordered that foundation. The first note, now Smooth…
- 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…
- 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…
- 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…
- Sampling a quantity from a distribution Done sample("x", T, distribution) makes a quantity at an address, scores it by a distribution and returns it, in place of quantity("x", T) followed by the distribution's score, and sample_in does the same…
- Reference measures and chart volumes of spaces Done Every continuous space of the core now has a reference measure, given through the log-volume of its retraction's chart, and the core's appendix no longer leaves curved types without one…
- The core Done The core of skoro, built to the charter: three crates in which a model can be built, queried and differentiated, but no distribution exists yet. skoro-tensor is the layer over burn, whose tensors are…
Built on by
- Queries and programs A query names what to compute from a snapshot and what is observed; compiled for a device and a precision, it becomes a program whose passes give values, tangents, gradients and Hessian-vector products in tangent charts.
- The normal distribution skoro's normal is the law of a point moved by normal noise through its space's chart, on every space whose chart is global, with an exact density and sampler, a scale in four forms, roles that estimators read, its tangent among them, and the Gaussian and improper Gaussian replacements of a retirement.
- The uniform distribution skoro's uniform distribution is the law of a space whose reference measure has finite mass, the rotations and the categorical spaces among them, with a constant term, an exact sampler on the host, and a residual of no components, so that a linearization reads it as a factor with no rows; it is how a model says that nothing is known of a quantity.