title: Cognitive Active Inference
type: package
status: stable
Cognitive Active Inference
A Python package for Active Inference agents, and an Obsidian vault of
linked pages that explain the mathematics, biology, cognitive science and
philosophy behind it. The package is the executable reference; the
vault is the explanation. Each side points at the other.
Status
After provisioning the locked dependencies, the package, test suite, and
offline documentation gates do not need network access. Manuscript HTML needs
Pandoc and pandoc-crossref; PDF also needs XeLaTeX. The no-render pipeline
skips those renderers. The GNN conformance job needs the upstream parser pinned in
specs/gnn-pin.json, and the OKN replay job needs the
captured cross-graph evidence in docs/okn/evidence/. The hosted quality
workflow is optional. The core package, the
knowledge base and the documentation gate need no credentials and no private
checkout.
Quick start
Python 3.11 or newer:
python -m pip install -e ".[dev]"
Build a two-state model, infer beliefs after an observation, and infer a
distribution over actions:
import numpy as np
from cognitive import ActiveInferenceDispatcher, DiscreteGenerativeModel, InferenceConfig, ModelState
model = DiscreteGenerativeModel(
A=np.array([[0.9, 0.1], [0.1, 0.9]]), # P(o | s)
B=np.stack([np.eye(2), np.array([[0.1, 0.9], [0.9, 0.1]])], axis=2), # P(s' | s, a)
C=np.array([0.0, 1.0]), # log-preference over o
D=np.array([0.5, 0.5]), # prior over s
E=np.array([0.5, 0.5]), # prior over a
)
dispatcher = ActiveInferenceDispatcher(
InferenceConfig(
method="variational",
policy_type="discrete",
temporal_horizon=2,
learning_rate=0.5,
precision_init=1.0,
seed=7,
),
model,
)
state = ModelState(model.D.copy(), model.E.copy(), 1.0, 0.0, 0.0)
beliefs = dispatcher.dispatch_belief_update(1, state) # q(s) after observing o = 1
policies = dispatcher.dispatch_policy_inference(state) # distribution over actions
assert np.isclose(beliefs.sum(), 1.0)
assert np.isclose(policies.sum(), 1.0)
The editable install also provides these commands:
| Command |
Purpose |
cognitive-benchmark |
Time the runtime components |
cognitive-build-manuscript |
Build the executable manuscript |
cognitive-validate-docs |
Run the documentation gate |
cognitive-verify-links |
Check [[wiki links]] |
cognitive-kb-index |
Check or regenerate the knowledge-base catalogs |
cognitive-export-rdf |
Export the knowledge base as RDF for the Open Knowledge Network |
cognitive-normalize-frontmatter |
Check or fix semantic_relations frontmatter |
cognitive-create-node |
Create a knowledge-base page from a template |
How one step works
An agent holds beliefs q(s) about hidden states. Each step it updates them from
what it observed, scores every candidate policy by expected free energy G, and
turns those scores into a distribution over actions.
flowchart LR
O["observation o"] --> BU["dispatch_belief_update"]
Q0["beliefs q(s)"] --> BU
BU --> Q1["posterior q(s)"]
Q1 --> EFE["expected free energy G per policy"]
GM["generative model A, B, C, D, E"] --> BU
GM --> EFE
EFE --> SM["softmax of -G / temperature, times prior E"]
SM --> PI["distribution over actions"]
PI --> ACT["action a"]
ACT -. "next step" .-> O
The generative model is five arrays, validated on construction:
The dispatcher offers three inference methods and discrete policy sequences with
explicit horizons, temperatures and seeds. All of its methods return finite,
normalized distributions.
flowchart TB
CFG["InferenceConfig"] --> D["ActiveInferenceDispatcher"]
D --> V["variational"]
D --> M["mean_field"]
D --> S["sampling"]
V --> OUT["normalized beliefs and policies"]
M --> OUT
S --> OUT
Method background: variational inference,
variational free energy,
message passing,
precision.
Expected free energy
expected_free_energy returns the canonical objective and its parts:
G = D_KL(q(o) || p*(o)) + E_q(s)[H(P(o | s))]
\_____ risk _____/ \____ ambiguity ____/
Ambiguity equals H[q(o)] - I(s; o), so the expected information gain is already
inside it. The package returns the gain as a fourth value for inspection and does
not subtract it from the total a second time. InferenceConfig.exploration_weight
adds an explicit information-seeking bias; it defaults to 0.0.
Derivation and intuition:
expected free energy,
in the free energy principle,
information gain,
KL divergence.
Package map
flowchart TB
subgraph pkg ["cognitive (code/tools/src)"]
MODELS["models/active_inference<br/>dispatcher, generative model,<br/>base model, homeostatic control"]
MATS["models/matrices<br/>MatrixOps, MatrixLoader"]
UTILS["utils<br/>matrix_utils, create_node,<br/>network visualization"]
VIZ["visualization<br/>MatrixPlotter, StateSpacePlotter"]
BENCH["benchmarks"]
end
subgraph things ["Things (code/Things)"]
SP["Simple_POMDP"]
CG["Continuous_Generic"]
end
subgraph scripts ["scripts (code/scripts)"]
GATES["validate_docs, verify_links,<br/>check_markdown_links,<br/>kb_index, export_rdf,<br/>normalize_frontmatter"]
MS["build_manuscript"]
MUT["mutation_check"]
end
MODELS --> MATS
MODELS --> UTILS
SP --> UTILS
CG --> UTILS
VIZ --> UTILS
GATES --> KB[("knowledge_base/")]
MS --> MAN[("docs/manuscript/")]
Agents
code/Things/ is installed as the Things package. Two
of its folders contain code; the others are design notes with no importable
Python.
| Agent |
Kind |
What it is |
Simple_POMDP |
code |
Discrete POMDP agent configured from a YAML path or dict; seeded, validated, with persistence, histories and expected-free-energy components |
Continuous_Generic |
code |
Precision-weighted generalized-coordinate updates; multi-frame GIF animation through ContinuousVisualizer |
Generic_POMDP |
design notes |
Matrix-configured discrete agent design |
Generic_Thing |
design notes |
The abstract definition of an agent |
Ant_Colony |
design notes |
Stigmergic foraging concept |
BioFirm, KG_Multi_Agent, Path_Network |
design notes |
A firm as an agent; agents on a knowledge graph; agents on a dynamic network |
Theory behind them:
POMDP framework,
generalized coordinates