skoro v0.0.0

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:

A scope builds the compilation graph
scope: a draftsnapshot ½ x0x_0 mm ζ\zeta σ\sigma x1x_1 z0z_0 z1z_1 step rr σ−2\sigma^{-2} r0r_0 r1r_1 ℓ1\ell_1 t1ℓ2\ell_2 t2ℓ3\ell_3 t3ℓ6\ell_6 t6ℓ7\ell_7 t7ℓ4\ell_4 t4ℓ5\ell_5 t5
  • Constant
  • Quantity
  • Mapped value
  • A term's log-density
  • input of
crates/skoro-core/tests/queries.rs lines 32–57
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();
Every step
  1. A writer of an empty model: its latest snapshot has no nodes.
  2. build opens 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.
  3. A constant: a value fixed when the model is built, and a root of the compilation graph.
  4. A quantity, at the address tick/0/x: an uncertain value, and another root.
  5. Its log-density ℓ1=−12 x0⋅x0\ell_1 = -\tfrac12 \, x_0 \cdot x_0 is four operations, each a node with an edge from each input. score then records ℓ1\ell_1 as the term t1, which scores x0x_0: a term names a node of the graph, and adds none.
  6. A second quantity, the landmark mm, and the term that scores it. The constant half is one node, read by both.
  7. Three more quantities: an inertial reading ζ\zeta, a scale σ\sigma and the next position x1x_1. The order quantities are made in is the model's ancestral order.
  8. step, computed from three quantities, gets an edge from each, and its square scores x1x_1 as t3.
  9. Each measurement is a quantity scored by a term of its residual.
  10. Two likelihood factors, t6 and t7: 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.
  11. 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 scope builds the compilation graph. The running example, line by line. Each blue or purple node stands for the operations on its line, drawn as one; the compilation graph has a node for each.

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:

A call of constants folds as it is added
scopesnapshotprogram of test.part, on the host xx [0.4, −0.9]ss 1.3ff = 0.3412q0q_0 q1q_1 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–342
fn 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
  1. define runs the body in a definition scope of its own, with a handle standing for each input.
  2. The operations the body applies build into the composite, not into any model: its nodes are kept, once, as the composite's body.
  3. A scope, and two constants in it.
  4. A call of the composite is one node of the model, with an edge from each argument.
  5. 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.
  6. 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.
  7. The program runs forward once, on the constants' values.
  8. 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.
  9. The scope publishes, and the snapshot holds the folded value: reading it needs no query and no program.
A call of constants folds as it is added. The composite's body is Σ(eq0⊙sin⁡q0) q1\Sigma(e^{q_0} \odot \sin q_0) \, q_1, from 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.

Branches share what they had
writer mainwriter branchwriter other s1s_1 s2s_2 s3s_3 s4s_4 xx xaa abb ba′a' 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
  1. A writer of an empty model.
  2. Its first scope publishes s1s_1, which holds the quantity xx.
  3. fork makes a second writer whose latest snapshot is s1s_1 itself: a branch, which shares everything and has copied nothing.
  4. A reader loads its writer's newest snapshot, from any thread. Both are at s1s_1.
  5. Building on main publishes s2s_2, built on s1s_1: it holds xx's node, the same allocation as s1s_1's, and a new quantity aa.
  6. Building on the branch publishes s3s_3, also built on s1s_1: xx again, and bb.
  7. Each reader now loads its own writer's newest snapshot.
  8. Neither sees the other's quantity. The handle of xx, made before the fork, names the same node on both.
  9. A fork of s3s_3 is a third writer, and its scope may take the address a, which only main had taken: addresses, like nodes, belong to a branch.
Branches share what they had. Each snapshot holds the nodes of its model; a later one is built on an earlier one, and shares its nodes rather than copying them.

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:

Built on by