Quickstart¶
Estimate the bias of a coin from ten flips. The work is a small package: a directory with a
manifest, qvr.toml, and two modules. The module coins.prior states the prior and the exact
posterior mean it implies, with a test that checks that mean. The module coins.model imports
it, declares the probabilistic program, and binds the program to its data in an experiment,
which qvr experiment run fits by Markov chain Monte Carlo. The fitted posterior can then be
compared with the exact one.
1. Install¶
This also installs the qvr command. Installation lists the platforms and
the optional extras.
2. Lay out the package¶
The package is a directory with this layout:
qvr.toml names the package, its version, and the modules other packages may import:
A module's path follows the directory layout: the file coins/prior.qvr is the module
coins.prior, and every module of the package coins has a path that starts with coins.
Packages lists every key of the manifest, and
Modules states how paths, imports, and exports work.
The data are ten flips, seven of them heads, in coins/flips.json:
3. The prior and its exact posterior¶
The coin's bias \(p\) has a \(\mathrm{Beta}(2, 2)\) prior. The Beta distribution is
conjugate to the Bernoulli likelihood, so after
\(h\) heads in \(n\) flips the posterior is \(\mathrm{Beta}(2 + h, 2 + n - h)\), whose mean is
\((2 + h) / (4 + n)\) (Gelman et al., 2013). Save the prior and this mean as coins/prior.qvr:
#! The pseudo-count of heads in the Beta prior on the coin's bias.
export define prior_heads() : Real !{} =
return 2.0
#! The pseudo-count of tails in the Beta prior on the coin's bias.
export define prior_tails() : Real !{} =
return 2.0
#! The posterior mean of the bias after `heads` heads in `flips` flips.
export define posterior_mean(heads : Real, flips : Real) : Real !{} =
let a <- prior_heads()
let b <- prior_tails()
return (a + heads) / (a + b + flips)
test "seven heads in ten flips" =
expect posterior_mean(7, 10) == 9/14 exactly
define declares a computation, and !{} says that it performs no effects. A declaration is
private to its module unless export precedes it, and a #! comment documents the declaration
that follows it, which qvr doc renders. The test sits beside the code it checks, but it is not
part of that code: compiling the module never reads it. qvr test runs it on the
reference machine over exact rational numbers, so
expect ... == 9/14 exactly compares the posterior mean with nine fourteenths exactly rather
than within a tolerance (Tests, properties, and examples).
4. The model and its experiment¶
Save the program and its experiment as coins/model.qvr:
import coins.prior as P
object Flip : FinSet 10
#! A coin of unknown bias, flipped once for each element of `Flip`.
export program bias : Flip -> Flip
let a <- P.prior_heads()
let b <- P.prior_tails()
let p <- sample Beta(concentration1=a, concentration0=b)
observe y : Flip <- Bernoulli(probs=p)
return p
experiment posterior
program bias
data y <- "flips.json" @blake3:cdad2a7b793c34d762026e2399b1f27ba6b2d8c386e7f52448770c57a24ede54
infer nuts(warmup = 300, draws = 500, chains = 2)
seed 0
import coins.prior as P reaches the exported names of coins.prior as P.prior_heads and
P.prior_tails, so the prior is stated once and both the test and the program read it.
object Flip : FinSet 10 declares a finite set with one element per flip. The sample step draws
the bias from its prior, and the observe step draws one flip for each element of Flip, a
plate of conditionally independent draws, and
scores the observed y under that likelihood. The name y is bound nowhere in the program, so it
is a data input that the run supplies.
The experiment binds the program to its data, its inference method, and its seed. It is a
checked declaration of the module, so every run it describes has a content hash, and every
number a run reports traces to the exact program, data, and configuration behind it
(Experiments). The data clause pins the
BLAKE3 hash of its file, so the experiment's hash
covers the data without reading them. Write the clause without the pin first, and qvr refuses
it with the pin to write:
error[experiment-data-pin]: coins/model.qvr:15:4: data y is not pinned, so the experiment's hash would not cover its content; write @blake3:cdad2a7b793c34d762026e2399b1f27ba6b2d8c386e7f52448770c57a24ede54 after the path
A file whose content later changes is refused the same way, naming the hash it has.
nuts(...) fits the posterior with the No-U-Turn Sampler (NUTS) (Hoffman and Gelman, 2014), here two
chains of 500 draws each after 300 steps of adaptation.
5. Check, lock, and test¶
Run each command from the package's directory. qvr check reads a module of the package in the
package's build and reports any error with its file, line, and column:
qvr lock resolves the manifest, checks every module of the package, and writes qvr.lock,
which pins each module by the content hash of its checked
declarations. Comments and formatting leave those hashes unchanged, so the lockfile changes only
when the code does. qvr test . runs the tests of every module below the directory:
ok coins/prior.qvr:15 test 'seven heads in ten flips'
1 passed (0 cached), 0 failed, 0 errors, 0 modules failed to load
A test passes once per content: its pass is cached under the hashes of the test and of the code
it tests, so a second qvr test . reports it as cached until either changes.
6. Run the experiment¶
The first line is the experiment's hash and the second the hash of its one point, both
shortened here; an experiment with a sweep clause has one point for each value. The posterior
mean of the bias lies within Monte Carlo error of the exact mean that the test
checked, \(9/14 \approx 0.643\), and its standard deviation lies near the exact one,
\(\sqrt{9 \cdot 5 / (14^2 \cdot 15)} \approx 0.124\). coins/model.qvr:posterior names the
module file and, after the colon, the experiment.
The run is stored under its hash in the package's cache, .qvr/cache. Running the experiment
again reads the stored record instead of sampling:
Editing the program, the prior module it imports, the data, or the experiment's clauses changes
the hash, and the next run computes the posterior again. qvr experiment hash prints the hashes
without running anything, and qvr experiment export writes the runs with an account of their
provenance (Experiments).
Next¶
- Checked model fitting: fitting from Python, with dimensions inferred from the data and inputs checked before inference
- Your first model: Bayesian linear regression, compared line by line with PyMC and NumPyro
- Concepts: composition of weighted relations, the choice of
Algebra, and the steps of a program - Modules and Packages: imports, exports, dependencies, lockfiles, and versions
- Object languages: a typed lambda calculus with binding, a normalizer, a typing judgment, and notation
- Composing a grammar: a categorial grammar built from a core, lexicon modules, and a semiring
Cited sources¶
Andrew Gelman, John B. Carlin, Hal S. Stern, David B. Dunson, Aki Vehtari, and Donald B. Rubin. Bayesian Data Analysis. Chapman and Hall/CRC, 3 edition, 2013. ISBN 9781439840955. URL: https://www.routledge.com/Bayesian-Data-Analysis/Gelman-Carlin-Stern-Dunson-Vehtari-Rubin/p/book/9781439840955.
Matthew D. Hoffman and Andrew Gelman. The No-U-Turn Sampler: Adaptively Setting Path Lengths in Hamiltonian Monte Carlo. Journal of Machine Learning Research, 15(47):1593–1623, 2014. URL: https://www.jmlr.org/papers/v15/hoffman14a.html.