skoro v0.0.0

A first model

Write a hierarchical normal with `sample`, generate from it and take its density and gradient given an observation, then see what the sugar is made of, from the tests of skoro itself.

This page starts from a model as it is usually written in skoro, with a distribution and the function sample, and works down from it. It first generates from the model and conditions it on an observation. It then shows the pieces underneath, each a little more general than the last: programs of plain arithmetic, the same model without the sugar, and terms written by hand beside likelihood factors. Each step quotes skoro’s own tests, so every line shown compiles and runs. The concepts explain each piece from the ground up; the links below go there when a step needs more than it shows.

A hierarchical model#

A point xx of the plane is drawn about the origin, and its squared range ρ\rho is measured with noise:

x∼N(0,σ02I2),ρ∣x∼N(∣x∣2,σ12).x \sim \mathcal N(0, \sigma_0^2 I_2), \qquad \rho \mid x \sim \mathcal N(|x|^2, \sigma_1^2).

In skoro the model reads as it is written above:

crates/skoro/tests/guide.rs lines 17–41
/// The standard deviations of `x` and of `ρ` given `x`.
const SIGMA0: f64 = 1.5;
const SIGMA1: f64 = 0.5;

/// `x ~ N(0, σ₀² I)` on the plane, and `ρ ~ N(|x|², σ₁²)`.
fn model() -> (Snapshot, Q<Vector<2>>, Q<Real>) {
    let mut writer = Writer::new();
    let (x, rho) = writer
        .build(|| {
            let origin = constant(Vector::<2>, [0.0, 0.0]);
            let x = sample(
                "x",
                Vector::<2>,
                Normal::on(Vector::<2>, origin, Scale::sd(SIGMA0)),
            );
            let rho = sample(
                "rho",
                Real,
                Normal::on(Real, (x * x).sum(), Scale::sd(SIGMA1)),
            );
            (x, rho)
        })
        .unwrap();
    (writer.snapshot(), x, rho)
}

A model is built inside the scope a writer opens, and published as a snapshot when the closure returns. sample(address, marker, distribution) makes a quantity at an address, of the space the marker names, and scores it by the distribution. Here the distribution is the normal, from the crate skoro-normal: Normal::on names its space, its mean and its scale, here a standard deviation. The mean of ρ\rho is computed from xx by ordinary arithmetic on its handle, (x * x).sum(), and is a value of the model like any other. Nothing names the writer inside the closure: everything goes into whichever model’s scope is open.

Generate from the joint#

Every quantity the normal scores comes with a sampler that draws it exactly, so the model can be generated: each quantity drawn in the order it was made, from its distribution given what was drawn before it, one row per key:

crates/skoro/tests/guide.rs lines 123–129
let (snapshot, x, rho) = model();
let generated = snapshot
    .generate(&Observations::new(), &Key::from_seed(11), 4000, &target)
    .unwrap();
let (xs, rhos) = (host(&generated.values, x), host(&generated.values, rho));
// Nothing is observed and both samplers are exact, so every draw weighs the same.
assert!(generated.log_weight.to_host().iter().all(|w| *w == 0.0));

generate takes the observations, here none, a random key, the number of rows, and a target. It gives the values drawn and an importance weight for each row; with nothing observed and exact samplers, every row weighs the same. The test goes on to check that the draws of xx and of ρ−∣x∣2\rho - |x|^2 have the means and variances the model gives them.

Condition on an observation#

A query names what to compute and what is observed. With ρ\rho observed, the model’s log-density is the joint density of xx and the observation, the posterior of xx up to a constant:

log⁡p(x,ρ)=−∣x∣22σ02−(ρ−∣x∣2)22σ12−2log⁡σ0−log⁡σ1−32log⁡2π.\log p(x, \rho) = -\frac{|x|^2}{2\sigma_0^2} - \frac{(\rho - |x|^2)^2}{2\sigma_1^2} - 2 \log \sigma_0 - \log \sigma_1 - \tfrac32 \log 2\pi .

Compiling the query from the snapshot, for a target, gives a program, and one pass of it gives the density and its gradient in xx at three points at once:

crates/skoro/tests/guide.rs lines 141–149
let (snapshot, x, rho) = model();
let query = Query::log_density().given(Observations::new().observe(rho, RHO));
let program = snapshot.compile(&query, &target).unwrap();
let (density, grad) = program.gradient(&at(x, &POINTS, &target)).unwrap();

let want: Vec<f64> = POINTS.iter().map(|&p| log_density(p)).collect();
close(&host(&density, NodeId::DENSITY), &want, &target);
let want: Vec<f64> = POINTS.iter().flat_map(|&p| gradient(p)).collect();
close(&grad.get(x).unwrap().to_host(), &want, &target);

The value is the closed form above, and the gradient is −x/σ02+2x(ρ−∣x∣2)/σ12-x / \sigma_0^2 + 2x(\rho - |x|^2) / \sigma_1^2, which the test’s own functions compute by hand. The test runs once at single precision and once at double on the CPU, and on a GPU through wgpu when that feature is on: target is each in turn. The model never changes; only the target does. On a GPU, testing::wgpu() first measures the adapter’s sine and cosine. If they err by more than skoro’s formulas are designed for, every wgpu test fails there, naming the error measured.

Programs of any value#

A query need not be of a density. Any value built in a scope can be compiled and differentiated, which is how the density above was: here a model has one quantity and no terms, and f is ∑i(xi2+sin⁡xi+xi)\sum_i (x_i^2 + \sin x_i + x_i), computed by the core’s primitive operations:

crates/skoro-core/tests/passes.rs lines 287–293
fn fan_out_accumulates_cotangents(target) {
    let mut writer = Writer::new();
    let (x, f) = writer
        .build(|| {
            let x = quantity("x", Vector::<2>).untyped();
            (x, (x * x + x.sin() + x).sum())
        })

The test’s helper compiles a query of the nodes it is given, from the writer’s latest snapshot:

crates/skoro-core/tests/passes.rs lines 132–137

fn compile(writer: &Writer, targets: &[QDyn], target: &Target) -> Arc<Program> {
    writer
        .snapshot()
        .compile(&Query::of(targets.iter().copied()), target)
        .unwrap()

The program is run at a value of x, one row of two entries, and its gradient compared with the derivative worked out by hand, 2xi+cos⁡xi+12 x_i + \cos x_i + 1:

crates/skoro-core/tests/passes.rs lines 294–299
    .unwrap();
let program = compile(&writer, &[f], &target);
let data = [0.3, -1.2];
let at = Values::new().with(x, value(&data, 1, 2, &target));
let (_, gradient) = program.gradient(&at).unwrap();
let expected: Vec<f64> = data.iter().map(|x| 2.0 * x + x.cos() + 1.0).collect();

untyped drops the static type Vector<2> of a handle, which this test does not need.

The model without the sugar#

sample does two things, and the hierarchical model can be written with each on its own. A quantity is made at an address with quantity, and the distribution’s score adds the term that scores it, a log-density, with its sampler:

crates/skoro/tests/guide.rs lines 43–57
/// The same model, each quantity made and then scored.
fn model_by_quantity_and_score() -> (Snapshot, Q<Vector<2>>, Q<Real>) {
    let mut writer = Writer::new();
    let (x, rho) = writer
        .build(|| {
            let origin = constant(Vector::<2>, [0.0, 0.0]);
            let x = quantity("x", Vector::<2>);
            Normal::on(Vector::<2>, origin, Scale::sd(SIGMA0)).score(x);
            let rho = quantity("rho", Real);
            Normal::on(Real, (x * x).sum(), Scale::sd(SIGMA1)).score(rho);
            (x, rho)
        })
        .unwrap();
    (writer.snapshot(), x, rho)
}

It builds the same model, and its density with ρ\rho observed is the same at every point. The two statements are what a model writes when it wants the handle of the term score gives back, to bind a role of its own on it or to give it another sampler; otherwise the term is found from the quantity it scores.

Terms written by hand#

A term need not come from a distribution at all. The core’s own score(quantity, log_density) adds any log-density built from the model’s values as the term of a quantity, and factor adds a likelihood factor, which scores nothing: the likelihood of data that is not a quantity of the model. Here a vehicle at x0x_0 and then x1x_1 measures a landmark mm from each position, its motion driven by an inertial reading ζ\zeta, and a second motion model is a likelihood factor over x0x_0, x1x_1 and a scale σ\sigma:

crates/skoro-core/tests/queries.rs lines 31–57
fn 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();

ζ\zeta and σ\sigma are scored by no term: they are parameters of the model, such as a sensor reading it is driven by. Query::log_density() is the sum of every term. Compiled and run with a value for each quantity, it equals the sum of the seven terms computed one at a time:

crates/skoro-core/tests/queries.rs lines 111–128
#[test]
fn query_density_is_the_sum_of_terms() {
    let e = example();
    let at = e.at([0.4, 0.1], &Target::host());
    let whole = density(&e.compile(&Query::log_density()), &at);
    let sum: f64 =
        e.t.iter()
            .map(|t| {
                host(
                    &e.compile(&Query::of([QDyn::from(*t)]))
                        .forward(&at)
                        .unwrap(),
                    *t,
                )[0]
            })
            .sum();
    assert!((whole - sum).abs() < 1e-12, "{whole} against {sum}");
}

With some quantities observed, by Query::log_density().given(observations), the same model gives the density of the others: the posterior of the vehicle’s positions and the landmark given the measurements, up to a constant, whose gradient is taken just as above, in the tangent charts of the free quantities.

A curved quantity#

The normal is written the same way on a curved space. Here two directions on a sphere measure an unknown direction xx, each with its own scale; a query observes them and estimates xx, or leaves them free and simulates them:

crates/skoro/tests/normal.rs lines 435–448
let mut writer = Writer::new();
let (x, z, terms) = writer
    .build(|| {
        let x = quantity("x", Sphere);
        let z = [quantity("z1", Sphere), quantity("z2", Sphere)];
        let terms = [
            Normal::on(Sphere, x, Scale::sd(sd1)).score(z[0]).id(),
            Normal::on(Sphere, x, Scale::sd(sd2)).score(z[1]).id(),
        ];
        (x, z, terms)
    })
    .unwrap();
let snapshot = writer.snapshot();
let given = Observations::new().observe(z[0], z1).observe(z[1], z2);

The concepts page on the normal says how its term, sampler and scale are made, and which spaces it takes.

How this came to be

The development behind this page, newest first: