Building a model
A model is built inside a scope a writer opens, by ordinary functions of handles, and published as an immutable snapshot that may be read from any thread or forked into a branch.
A model is built forward, the way it is thought of: a quantity, then what is computed from it, then the next quantity. Building happens inside a scope that a writer opens, by ordinary functions of handles that name no writer, device or precision, and the writer publishes what was built as an immutable snapshot. This page describes the writer, the scope and its functions, what happens on a mistake, and snapshots and branches.
The writer and its scope#
crates/skoro-core/src/writer.rs lines 33–47/// Runs `body` with a building scope open on this thread, and publishes what it built. A
/// scope that recorded a failure publishes nothing and returns the failure; one that panics
/// drops its draft as it unwinds.
pub fn build<R>(&mut self, body: impl FnOnce() -> R) -> Result<R, Failure> {
let draft = Draft::new(self.latest.0.as_ref().clone());
let (result, frame) = scope::open(Frame::Scope(draft), body);
let Frame::Scope(draft) = frame else {
unreachable!("build gets back the scope it opened")
};
if let Some(failure) = draft.failure {
return Err(failure);
}
self.publish(draft.model);
Ok(result)
}build opens a building scope on the current thread and runs the closure in it.
Every function that builds (making a quantity, applying an operation, adding a term) adds its node to the innermost open scope, which is why a function of handles needs no model passed to it: the same function builds into whichever model’s scope it is called in.
When the closure returns, the writer publishes the new model.
The scope’s own functions make the roots of a model, its quantities and constants, and place quantities at addresses:
crates/skoro-core/src/scope.rs lines 329–347/// A quantity of `marker`'s space at `address`, under the open namespaces (`AddressTaken`).
#[track_caller]
pub fn quantity<T: Declares>(address: impl Into<Address>, marker: T) -> Q<T> {
let (address, space) = (address.into(), marker.space());
let location = Location::caller();
Q::from_id(build(location, |draft, prefix| {
draft.quantity(prefix.join(&address), space)
}))
}
/// A quantity of `space` at `address`, under the open namespaces (`AddressTaken`).
#[track_caller]
pub fn quantity_in(address: impl Into<Address>, space: Space) -> QDyn {
let address = address.into();
let location = Location::caller();
QDyn::from_id(build(location, |draft, prefix| {
draft.quantity(prefix.join(&address), space)
}))
}crates/skoro-core/src/scope.rs lines 375–386/// A constant of `marker`'s space (`ValueShape` when the value does not fit it).
#[track_caller]
pub fn constant<T: Declares>(marker: T, value: impl IntoHostValue<T>) -> Q<T> {
let (space, value) = (marker.space(), value.into_host_value());
let location = Location::caller();
Q::from_id(build(location, |draft, _| draft.constant(space, value)))
}
/// Runs `body` with `prefix` prefixed to the addresses of the quantities it makes and looks up.
pub fn namespace<R>(prefix: impl Into<Address>, body: impl FnOnce() -> R) -> R {
open(Frame::Namespace(prefix.into()), body).0
}A quantity is an uncertain value of the model, made at an address: a path of names and indices such as tick/1/x, where a segment of digits is an index. namespace prefixes the addresses of everything made inside it, so the model of one tick can be written once, as a function, and called under tick/0, tick/1 and so on. lookup finds a quantity by its address under the open namespaces.
A constant is a value fixed when the model is built; a constant and anything computed from constants alone is folded into a value as soon as it is added.
The compilation graph#
What a scope builds is the model’s compilation graph. Its nodes are the model’s values: the quantities and constants, which are its roots, and the outputs of operations, among them the log-densities of terms. Its edges run from each input of an operation to its output. A scope only adds: it builds nodes on top of the previous snapshot’s, and nothing already published changes. Nodes leave the graph only through a retirement, which removes the quantities it retires, what is computed from them, and the values it leaves needed by nothing.
Here is a scope building the compilation graph of a model of a vehicle and a landmark, to which the page on terms returns, one line at a time. Step through it, or play it:
- Constant
- Quantity
- Mapped value
- A term's log-density
- input of
crates/skoro-core/tests/queries.rs lines 32–57let 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();Every step
- A writer of an empty model: its latest snapshot has no nodes.
buildopens a scope on this thread: a draft of the model, copied from the writer's latest snapshot, pushed on the thread's stack of frames. Every building function below adds its node to the innermost draft, which is why none of them is passed a model.- A constant: a value fixed when the model is built, and a root of the compilation graph.
- A quantity, at the address
tick/0/x: an uncertain value, and another root. - Its log-density is four operations, each a node with an edge from each input.
scorethen records as the termt1, which scores : a term names a node of the graph, and adds none. - A second quantity, the landmark , and the term that scores it. The constant
halfis one node, read by both. - Three more quantities: an inertial reading , a scale and the next position . The order quantities are made in is the model's ancestral order.
step, computed from three quantities, gets an edge from each, and its square scores ast3.- Each measurement is a quantity scored by a term of its residual.
- Two likelihood factors,
t6andt7: terms that score nothing. A function of handles never asks which model it builds into, so the same code could as well have built these into a branch. - The closure returns, and no building function recorded a failure, so the writer publishes the draft as its new snapshot: an immutable model, cheap to clone, from which queries are compiled.
A node all of whose inputs are fixed in the model, constants or nodes folded before it, is folded as it is added: its operation is lowered for the host and run once, at double precision, and the node keeps the value. A call of a composite is folded the same way, by a program compiled from the composite’s body:
test.part, on the host [0.4, −0.9] 1.3 = 0.3412 exp sin × Σ × - Constant
- A composite's input
- Mapped value
- A call of a composite
- Folded value
- input of
- binds an input
crates/skoro-core/tests/composite.rs lines 325–342fn a_call_of_constants_folds_when_added() {
let part = Composite::define(
"test.part",
Vec::new(),
&[Space::Vector(2), Space::Real],
|q| in_place(q[0], q[1]),
)
.unwrap();
let mut writer = Writer::new();
let f = writer
.build(|| {
let x = constant(Vector::<2>, [0.4, -0.9]).untyped();
let s = constant(Real, 1.3).untyped();
part.call(&[x, s])
})
.unwrap();
let snapshot = writer.snapshot();
let folded = snapshot.node(f.id()).unwrap().value().unwrap().clone();Every step
defineruns the body in a definition scope of its own, with a handle standing for each input.- The operations the body applies build into the composite, not into any model: its nodes are kept, once, as the composite's body.
- A scope, and two constants in it.
- A call of the composite is one node of the model, with an edge from each argument.
- Every input of the call is fixed in the model, so the scope folds the node as it adds it: it lowers the call's operation for the host, at double precision, and a composite lowers to itself.
- The lowering compiles the composite into a program of its own, binding its inputs to the constants. A lowering keeps each composite it compiles, by name and parameters, so one it meets twice is compiled once.
- The program runs forward once, on the constants' values.
- The node keeps the value it computed, and is fixed in the model from now on: a node built on it alone folds in turn, and a query reads it as a constant.
- The scope publishes, and the snapshot holds the folded value: reading it needs no query and no program.
in_place.Mistakes, and where they were made#
Building never panics on a mistake in the model.
Each building function checks its inputs (that they exist in this model, that their spaces suit the operation, that an address is not taken) and, on a fault, records it and returns a failed handle.
Everything built on a failed handle fails in turn, and the scope publishes nothing. build then returns the first fault, with the line of user code that caused it:
crates/skoro-core/tests/building.rs lines 52–75#[test]
fn scope_reports_the_first_failure_and_where() {
let mut writer = Writer::new();
let mut line = 0;
let failure = writer
.build(|| {
let x = quantity("x", Real);
let v = quantity("v", Vector::<2>);
line = line!() + 1;
let first = add(x, v);
add(first, x);
quantity("x", Real); // a second failure, not reported
})
.unwrap_err();
assert!(matches!(
failure.error,
Error::SpaceMismatch {
operation: "skoro.add",
..
}
));
assert_eq!(failure.location.line(), line);
assert_eq!(failure.location.file(), file!());
}So the failure points at add(x, v), where a real number was added to a vector, rather than at the second mistake or at whatever later tried to use the model.
Snapshots, readers and branches#
A snapshot is an immutable model, cheap to clone, which the queries of the next pages are compiled from.
A writer hands out its latest snapshot, and a Reader that loads the newest one from any thread, so estimators can run on snapshots while the writer goes on building.
A snapshot can also be forked into a writer of its own: a branch, which shares everything with the snapshot it came from and changes independently of it. This is how a model is held under several hypotheses at once.
mainwriter branchwriter other x a b a- Snapshot
- Quantity
- is built on by
- holds
crates/skoro-core/tests/branches.rs lines 41–55#[test]
fn branches_do_not_see_each_other() {
let mut main = Writer::new();
main.build(|| quantity("x", Real)).unwrap();
let mut branch = main.snapshot().fork();
let (main_reader, branch_reader) = (main.reader(), branch.reader());
let a = main.build(|| quantity("a", Real)).unwrap();
let b = branch.build(|| quantity("b", Real)).unwrap();
let (main, branch) = (main_reader.latest(), branch_reader.latest());
assert!(main.node(a.id()).is_some() && main.node(b.id()).is_none());
assert!(branch.node(b.id()).is_some() && branch.node(a.id()).is_none());
// Each branch may use an address the other took.
let mut other = branch.fork();
assert!(other.build(|| quantity("a", Real)).is_ok());
}Every step
- A writer of an empty model.
- Its first scope publishes , which holds the quantity .
forkmakes a second writer whose latest snapshot is itself: a branch, which shares everything and has copied nothing.- A reader loads its writer's newest snapshot, from any thread. Both are at .
- Building on
mainpublishes , built on : it holds 's node, the same allocation as 's, and a new quantity . - Building on the branch publishes , also built on : again, and .
- Each reader now loads its own writer's newest snapshot.
- Neither sees the other's quantity. The handle of , made before the fork, names the same node on both.
- A fork of is a third writer, and its scope may take the address
a, which onlymainhad taken: addresses, like nodes, belong to a branch.
A handle stays valid on every branch that shares its node, so the quantities made before the fork are named the same way on each.
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…
- 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…
- 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…
- 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
- 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.