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 of the plane is drawn about the origin, and its squared range is measured with noise:
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 is computed from 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–129let (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 and of have the means and variances the model gives them.
Condition on an observation#
A query names what to compute and what is observed. With observed, the model’s log-density is the joint density of and the observation, the posterior of up to a constant:
Compiling the query from the snapshot, for a target, gives a program, and one pass of it gives the density and its gradient in at three points at once:
crates/skoro/tests/guide.rs lines 141–149let (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 , 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 , computed by the core’s primitive operations:
crates/skoro-core/tests/passes.rs lines 287–293fn 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, :
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 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 and then measures a landmark from each position, its motion 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(); and 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 , each with its own scale; a query observes them and estimates , or leaves them free and simulates them:
crates/skoro/tests/normal.rs lines 435–448let 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:
- 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 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…
- Accuracy on the GPU Done Three checks of single against double precision passed on the CPU and failed on a wgpu adapter, where CI cannot run them: two of the pose's left Jacobian in the rotations' tests, and one of 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…
- Normal distributions Done skoro's first distribution, the normal, returns as one distribution for every space whose chart is global and whose volume is known: the law of the mean moved by normal noise through its chart, so…
- 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…