A runnable companion to Smith, Friston, and Whyte’s 2022 active inference tutorial. Start with two hidden causes and one observation, then work through explore–exploit decisions, learning, hierarchical auditory inference, and behavioral fitting. Models are written in Generalized Notation Notation (GNN), and the manuscript links its calculations to model inputs and inference traces. The software package is Step by Step GNN (step-by-step); the course it builds is titled Step-by-Step Active Inference.
When a verified course archive is available, download and extract step-by-step-gnn.zip from the releases. Open pdf/step-by-step-active-inference.pdf for offline reading or web/index.html for linked navigation. Keep the extracted directories together so the HTML can find the figures, models, tables, and traces.
The reading guide follows the source tutorial in order. Each of the six GNN labs asks you to predict what a model change will do, edit one assumption, then compare the trace with the baseline. Appendix G collects the commands. The lesson registry maps each module to its source pages and runnable scenarios.
The authored manuscript lives in docs/manuscript/. A build copies the chapters into the bundle’s manuscript/ directory. Links from the chapters to figures, traces, and other generated files resolve in the built or extracted bundle. In the checkout, catalog/ holds the coverage, lesson, and reference registries, and the numerical parity notes describe their evidence.
Install uv. Run the commands from the root of the repository, using the source revision for the edition you are reading.
uv python install 3.14
uv sync --locked
uv run --locked step-by-step validate
uv run --locked step-by-step lesson
uv run --locked step-by-step lesson foundations --output output/foundationsA working installation prints this line from validate:
Strictly validated and extracted 17 native GNN models. Checked 107 paper entries across 9 learning modules.
Open output/foundations/summaries/perception.csv beside the shaded-disc model. The example observation has evidence 0.46 and gives the concave interpretation posterior probability about 0.8804. Compare the prior and likelihood entries that produce that result. Use step-by-step list to find an individual scenario.
Make a working copy of the disc model. Change ObservedOutcomes={(0)} to ObservedOutcomes={(1)} in the copy and predict the new posterior.
mkdir -p output
cp models/perception.md output/disc.mduv run --locked gnn validate --strict output/disc.md
uv run --locked step-by-step run --scenario perception \
--model output/disc.md --output output/disc-labThen ask what the edit changed. Give the baseline run first.
uv run --locked step-by-step compare output/foundations output/disc-labThe report shows the model line you edited, then each summary cell that moved with its old and new value: the concave posterior falls from about 0.8804 to about 0.0833. It also names the trace fields that differ in each record. Add --field NAME to print both values of a trace field. Differences at the level of floating-point rounding are left out.
The run preserves the edited model, its compiled export, and its own traces. Choose an output path that does not exist yet for each run. Without --output, a run writes to output/<scenario>.
An override replaces the values a scenario reads from its own model. step-by-step list marks the scenarios that accept one with [--model]. Start from a copy of that model and keep its variable names, array shapes, and category order.
| Scenarios | Copy this model |
|---|---|
perception |
models/perception.md |
perception-figure3, perception-figure5 |
models/perception_figure3.md, models/perception_figure5.md |
hmm |
models/message_passing.md |
precision, habitual |
models/policy_precision.md |
explore-averse, explore-seeking, learning, learning-rs3, reversal, reversal-rs3 |
models/explore_exploit.md |
auditory-standard, auditory-deviant, auditory-control, auditory-standard-intended, auditory-deviant-intended |
models/auditory_hierarchy.md with --model-role upper, or models/auditory_tone.md with --model-role lower |
The checks come in two layers. gnn validate --strict checks that the required sections are present, that variables and connections parse and name declared variables, and that each array has its declared shape. It does not test probabilities. step-by-step run --model repeats those checks, then asks the GNN extractor to confirm that every likelihood, transition, and prior is nonnegative and sums to one, with the offending line named. It also confirms that each array has the shape its scenario expects and that observations name an existing category. The state-space sizes and the connections describe the graph for readers and for the compiled export. Inference takes its dimensions from the named arrays, so resizing a variable or redrawing a connection does not add a state to a scenario.
| Look for | Where to start |
|---|---|
| Published panel, equation, table, or exercise | coverage.json gives the source locator, native scenarios, and generated files. It sits at the root of a built bundle, and its source is catalog/coverage.json in the checkout. The CSV table names follow the source tutorial’s IDs. |
| Task assumptions and axis order | models/ preserves the authored GNN. compiled-models/ contains the typed graph, extracted POMDP inputs, and source hash. |
| Seed, model override, or inference profile | scenarios/<id>.json records the seed, model hashes, and applicable replay or inference settings. Its random_source is archived-reference-draws when the run replays draws captured from the reference run, seeded-generator when the seed drives a fresh history, and none for a calculation that ignores the seed. |
| A belief update or an observed action | traces/<id>.jsonl is the detailed record. Begin in summaries/<id>.csv to choose a trial or participant. |
| Figure image or auditory projection | The manuscript’s download index links every SVG. A full build writes figures/ with PNG copies and tables/. An auditory run writes auditory-projections/ with synchronized samples for the waveform displays. |
| Build and verification evidence | artifacts.json records the source revision, runtime, and file hashes. render.json records the PDF and HTML cross-reference checks. See the numerical parity notes for the SPM evidence. |
Generate the example CSV and fit it with or without a free learning rate.
uv run --locked step-by-step run --scenario fitting --output output/fit-demo
uv run --locked step-by-step fit \
--data output/fit-demo/data/synthetic-behavior.csv \
--estimate-eta --output output/my-fitFor your own history, use the header and ordering below. Number each participant’s trials from 1 with no gaps. Include exactly one row for each decision 1 and 2. The first observation of the start state is implicit. An action comes before its outcome within each row.
participant,trial,decision,action,outcome
example,1,1,hint,left
example,1,2,left,win
example,2,1,right,loss
example,2,2,start,noneLabels are lowercase. Hints admit left and right outcomes. Machine choices admit loss and win. A direct machine choice is followed by the forced start,none row. The output fits.json contains the estimates, intervals, likelihood, evidence, and optimization trajectory for each participant. fitted_parameters names the coordinates that were estimated, in the order used by position, covariance and interval, and fixed_parameters names the ones held at their prior value. Give step-by-step compare two fit directories to set their estimates side by side. It compares evidence only when the per-participant history_sha256 fingerprints match. Refit older outputs to add fingerprints. estimates uses natural units. position and covariance use the fitting coordinates: logarithms of alpha and rs, and the log odds of eta when it is estimated. interval holds the lower bounds in its first row and the upper bounds in its second, in that parameter order. Add --inference-mode spm-publication --optimizer spm-newton for the fitting conventions in the matched reference. A fit that stops before converging is reported as a warning and still written; add --strict to make the command exit with status 1 in that case.
The Figure 17 scenario uses the explore–exploit task and group GNN. It regenerates the controlled histories, fits the individuals, and runs the recovery and group analyses. Both supported seeds, 20220204 and 7, can run in either averaging mode.
uv run --locked step-by-step run --scenario figure17 --seed 7 \
--output output/figure17-stable
uv run --locked step-by-step run --scenario figure17 --seed 7 \
--bma-mode literal --output output/figure17-literalThe default stable mode uses a factorized log-determinant calculation for model evidence. The literal mode uses the archived SPM relative evidence to weight the retained models. Both modes compute the individual fits, group reduction, and coefficient samples in GNN. At seed 7, draws 84 and 759 show how the same uniform can cross different selection boundaries. Counting from zero, they are entries 83 and 758 of group.averaged.model_indices in data/figure17-run.json, and adding one to a stored value gives the candidate number. Find each run’s averaging mode and evidence source in scenarios/figure17.json. The reference notes give the matched selections, tolerances, and raw-data recheck.
A scientific build runs the scenarios and regenerates the figures, tables, and traces. For the PDF and HTML, install XeLaTeX, TeX Gyre OpenType and math fonts, BibTeX, Poppler, and compatible Pandoc and pandoc-crossref binaries. The tested versions are Pandoc 3.14 and pandoc-crossref 0.3.26. The local CI guide gives installation commands for macOS and Linux.
uv run --locked step-by-step build --scientific-only --output output/sciencePrepare a separate docxology/template checkout at the pinned revision. Use an absolute path for TEMPLATE_ROOT.
export TEMPLATE_ROOT="/absolute/path/to/prepared/template"
git init "$TEMPLATE_ROOT"
git -C "$TEMPLATE_ROOT" fetch --depth 1 https://github.com/docxology/template.git \
ea8d0d47339fdc59b9447a5331569fa91a90426b
git -C "$TEMPLATE_ROOT" checkout --detach FETCH_HEAD
uv sync --project "$TEMPLATE_ROOT" --locked --no-default-groups
uv run --locked step-by-step build --output output/tutorialAdd --bma-mode literal and choose a fresh output directory to render the literal edition. The build’s Figure 17 caption and comparison labels follow the selected mode. Add --spm-witnesses /absolute/path/to/spm-witnesses to include the exact archived MATLAB-format files. The build validates their hashes against the two comparison catalogs.
The project uses local CI only; there is no hosted workflow. Commit your changes, then run the local CI script from the checkout. Without options it runs lint, the format check, the tests, validation, strict model checks, and two independent scientific builds compared as whole trees.
scripts/local_ci.shA passing run ends with Local CI passed for <commit>. Receipt: <path>. With a warm package cache it took about 10 minutes on an Apple-silicon Mac, and the release run below about 30. The release run needs the spm-witnesses/ directory from a release archive and the rendering tools. Without them you can run everything except --witnesses and --render.
The numerical claim is agreement with the authors’ companion scripts and SPM12 r7771 running in GNU Octave 8.4.0 on one platform, on matched inputs at seeds 20220204 and 7. The article’s own driver shuffles its seed, so its printed random histories cannot be regenerated; Figure 17 uses newly generated seeded histories. The six synthetic participants illustrate the fitting workflow and support no empirical conclusion. The numerical parity notes give the quantities and tolerances.
For a release, set witnesses to the reviewed archive’s spm-witnesses/ directory and prepare the renderer as above. The release run also repeats the reference comparisons, renders both editions, and packages the stable edition next to the run’s receipt.
witnesses="/absolute/path/to/step-by-step-gnn/spm-witnesses"
scripts/local_ci.sh --witnesses "$witnesses" --renderUse the archive from a passing release run, or a fully rendered build with the reviewed witnesses. Packaging checks each listed file’s SHA-256 and size. Packaging refuses a bundle built without a Git revision or with uncommitted changes. Confirm that the manifest revision matches the integrated commit, attach the archive to its release through the repository’s reviewed publication workflow, then verify the downloaded asset’s SHA-256 against the packaged file.
The documentation index links to the contributor guide,
the local gate, and the numerical parity procedure. CITATION.cff
holds the citation for this companion.
Cite the edition you used. Version 1.0.0 is doi:10.5281/zenodo.24664985. CITATION.cff carries the same record, and each PDF and HTML edition prints its own DOI on the cover. Use the DOI and the matching release to check availability of the PDF and complete bundle.
The software and the course content carry different licenses, divided by directory.
| Material | License |
|---|---|
Code in src/, scripts/, and tests/, and the packaging files |
GNU General Public License, version 2 or later (GPL-2.0-or-later) |
Course content in models/, catalog/, and docs/, this README, and the built PDF, HTML, figures, tables, traces, and summaries |
Creative Commons Attribution 4.0 International (CC-BY-4.0) |
Copyright 2026 Daniel Ari Friedman. The group-analysis code reproduces routines from SPM12, which is distributed under the GNU General Public License, version 2 or later. The source tutorial is published under CC BY-NC-ND 4.0 and remains its authors’ work; this license covers the companion’s own text, models, and figures, not the article or the authors’ scripts. The files in spm-witnesses/ are numerical outputs of the authors’ scripts and SPM12, archived for verification.
- Smith, R., Friston, K. J., and Whyte, C. J. (2022), A step-by-step tutorial on active inference and its application to empirical data. Published article · Open-access record and license
- Publication-era supplemental scripts and SPM12 r7771 define the reference calculations checked in GNU Octave.
- Smékal, J., and Friedman, D. A. (2023), Generalized Notation Notation for Active Inference Models. Notation article · Pinned parser and extraction software, v5.4.0