cogant.runtime
The cogant.runtime package provides the Active Inference agent runtime —
the perception-action loop that consumes synthesized matrices (or any
object exposing A, B, C, D) and executes belief updates,
action selection, and multi-episode learning.
Package
cogant.runtime
Active Inference agent runtime for COGANT synthesized packages.
This module provides an executable perception-action loop that operates
on the A/B/C/D matrices produced by :func:cogant.reverse.synthesizer.synthesize_package.
The categorical arithmetic is pure Python without numerical dependencies.
The typed trace layer uses Pydantic; the installed package requires its
declared dependencies.
Public API
- :class:
AgentConfig-- configuration dataclass (max_steps, convergence, etc.) - :class:
AgentStep-- immutable record of one inference step - :class:
AgentRuntime-- the core runtime wrapping a matrices module - :func:
run_n_steps-- convenience: run N steps - :func:
run_until_convergence-- convenience: run until belief stabilises
AgentConfig
dataclass
Configuration for the Active Inference agent loop.
Attributes:
| Name | Type | Description |
|---|---|---|
max_steps |
int
|
Maximum number of inference steps before forced halt. Must be non-negative. |
convergence_threshold |
float
|
KL divergence threshold below which the agent considers its belief to have converged. Must be in (0, 1). |
Source code in py/cogant/runtime/config.py
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 | |
__post_init__()
Validate configuration after initialization.
Raises:
| Type | Description |
|---|---|
ValueError
|
If any configuration value is invalid. |
Source code in py/cogant/runtime/config.py
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | |
from_yaml(path)
classmethod
Load configuration from a YAML file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path to YAML file with keys matching AgentConfig fields. |
required |
Returns:
| Type | Description |
|---|---|
AgentConfig
|
Loaded AgentConfig instance. |
Raises:
| Type | Description |
|---|---|
ImportError
|
If pyyaml is not installed. |
FileNotFoundError
|
If the file does not exist. |
ValueError
|
If YAML contains invalid values. |
Example
cfg = AgentConfig.from_yaml("config.yaml")
Source code in py/cogant/runtime/config.py
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | |
to_yaml(path)
Save configuration to a YAML file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path where YAML file will be written. |
required |
Raises:
| Type | Description |
|---|---|
ImportError
|
If pyyaml is not installed. |
Example
cfg = AgentConfig(max_steps=200) cfg.to_yaml("config.yaml")
Source code in py/cogant/runtime/config.py
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 | |
with_defaults()
classmethod
Create a new AgentConfig with sensible defaults.
Returns:
| Type | Description |
|---|---|
AgentConfig
|
A new AgentConfig instance with default values. |
Example
cfg = AgentConfig.with_defaults() print(cfg.max_steps) 100
Source code in py/cogant/runtime/config.py
115 116 117 118 119 120 121 122 123 124 125 126 127 | |
AgentRuntime
Mutable agent matrices with shared categorical inference and learning.
Source code in py/cogant/runtime/loop.py
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 | |
step(state_dist, obs_idx, t=0)
Filter then choose minimum one-step EFE, with lowest-index ties.
Source code in py/cogant/runtime/loop.py
52 53 54 55 56 57 58 59 60 61 62 63 64 | |
run_n_steps(n, initial_state=None)
Run a deterministic model rollout using modal predicted observations.
Source code in py/cogant/runtime/loop.py
66 67 68 69 70 71 72 73 74 75 76 77 | |
update_A_from_counts(obs_state_counts, learning_rate=0.1)
Blend conditional P(observation | state) counts, leaving unseen states unchanged.
Source code in py/cogant/runtime/loop.py
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 | |
AgentStep
dataclass
One cycle: posterior and VFE precede control; state_dist follows control.
Source code in py/cogant/runtime/records.py
6 7 8 9 10 11 12 13 14 15 16 | |
EpisodeResult
dataclass
Observed posterior soft counts and the final corrected posterior.
Source code in py/cogant/runtime/records.py
19 20 21 22 23 24 25 26 27 28 | |
MultiEpisodeResult
dataclass
Episode metrics and learned-prior snapshots.
Source code in py/cogant/runtime/records.py
31 32 33 34 35 36 37 38 39 | |
Loop
AgentRuntime, run_n_steps, run_until_convergence, and the
multi-episode run_multi_episode learning driver.
cogant.runtime.loop
Matrix-based perception, finite-policy selection, and episode learning.
AgentStep
dataclass
One cycle: posterior and VFE precede control; state_dist follows control.
Source code in py/cogant/runtime/records.py
6 7 8 9 10 11 12 13 14 15 16 | |
EpisodeResult
dataclass
Observed posterior soft counts and the final corrected posterior.
Source code in py/cogant/runtime/records.py
19 20 21 22 23 24 25 26 27 28 | |
MultiEpisodeResult
dataclass
Episode metrics and learned-prior snapshots.
Source code in py/cogant/runtime/records.py
31 32 33 34 35 36 37 38 39 | |
AgentRuntime
Mutable agent matrices with shared categorical inference and learning.
Source code in py/cogant/runtime/loop.py
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 | |
step(state_dist, obs_idx, t=0)
Filter then choose minimum one-step EFE, with lowest-index ties.
Source code in py/cogant/runtime/loop.py
52 53 54 55 56 57 58 59 60 61 62 63 64 | |
run_n_steps(n, initial_state=None)
Run a deterministic model rollout using modal predicted observations.
Source code in py/cogant/runtime/loop.py
66 67 68 69 70 71 72 73 74 75 76 77 | |
update_A_from_counts(obs_state_counts, learning_rate=0.1)
Blend conditional P(observation | state) counts, leaving unseen states unchanged.
Source code in py/cogant/runtime/loop.py
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 | |
Config
AgentConfig — knobs for convergence threshold, max steps, and
learning-update hyperparameters.
cogant.runtime.config
Agent configuration for the Active Inference runtime.
Uses a plain dataclass rather than pydantic to maintain the zero-dependency constraint of the categorical execution core.
AgentConfig
dataclass
Configuration for the Active Inference agent loop.
Attributes:
| Name | Type | Description |
|---|---|---|
max_steps |
int
|
Maximum number of inference steps before forced halt. Must be non-negative. |
convergence_threshold |
float
|
KL divergence threshold below which the agent considers its belief to have converged. Must be in (0, 1). |
Source code in py/cogant/runtime/config.py
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 | |
__post_init__()
Validate configuration after initialization.
Raises:
| Type | Description |
|---|---|
ValueError
|
If any configuration value is invalid. |
Source code in py/cogant/runtime/config.py
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | |
from_yaml(path)
classmethod
Load configuration from a YAML file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path to YAML file with keys matching AgentConfig fields. |
required |
Returns:
| Type | Description |
|---|---|
AgentConfig
|
Loaded AgentConfig instance. |
Raises:
| Type | Description |
|---|---|
ImportError
|
If pyyaml is not installed. |
FileNotFoundError
|
If the file does not exist. |
ValueError
|
If YAML contains invalid values. |
Example
cfg = AgentConfig.from_yaml("config.yaml")
Source code in py/cogant/runtime/config.py
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | |
to_yaml(path)
Save configuration to a YAML file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path where YAML file will be written. |
required |
Raises:
| Type | Description |
|---|---|
ImportError
|
If pyyaml is not installed. |
Example
cfg = AgentConfig(max_steps=200) cfg.to_yaml("config.yaml")
Source code in py/cogant/runtime/config.py
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 | |
with_defaults()
classmethod
Create a new AgentConfig with sensible defaults.
Returns:
| Type | Description |
|---|---|
AgentConfig
|
A new AgentConfig instance with default values. |
Example
cfg = AgentConfig.with_defaults() print(cfg.max_steps) 100
Source code in py/cogant/runtime/config.py
115 116 117 118 119 120 121 122 123 124 125 126 127 | |
Metrics
Numerically-stable free-energy and KL divergence helpers that back the runtime loop.
cogant.runtime.metrics
Episode statistics and exact categorical variational free energy.
EpisodeMetrics
dataclass
Metrics for a single learning episode.
Attributes:
| Name | Type | Description |
|---|---|---|
episode_id |
int
|
Unique episode identifier. |
n_steps |
int
|
Number of steps in the episode. |
mean_free_energy |
float
|
Mean VFE across the episode. |
final_free_energy |
float
|
VFE at the last step. |
n_unique_obs |
int
|
Number of unique observations seen. |
action_entropy |
float
|
Shannon entropy of action distribution. |
Source code in py/cogant/runtime/metrics.py
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | |
to_csv_row()
Convert metrics to a dictionary suitable for CSV logging.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with string keys and scalar values for CSV export. |
Example
metrics = EpisodeMetrics(episode_id=1, n_steps=5, ...) row = metrics.to_csv_row() import csv csv.DictWriter(f, fieldnames=row.keys()).writerow(row)
Source code in py/cogant/runtime/metrics.py
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | |
RunMetrics
dataclass
Aggregate metrics for a multi-episode learning run.
Attributes:
| Name | Type | Description |
|---|---|---|
episodes |
list[EpisodeMetrics]
|
List of per-episode metrics. |
total_steps |
int
|
Total inference steps across all episodes. |
Source code in py/cogant/runtime/metrics.py
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 | |
plot_free_energy()
Plot mean and final VFE trajectories (if matplotlib available).
Returns:
| Type | Description |
|---|---|
Any
|
A matplotlib Figure object if matplotlib is installed and there |
Any
|
are episodes to plot; None otherwise. |
Example
metrics = RunMetrics(episodes=[...]) fig = metrics.plot_free_energy() if fig: ... fig.show()
Source code in py/cogant/runtime/metrics.py
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 | |
summary_statistics()
Compute summary statistics over all episodes.
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
Dictionary with mean/std/min/max for: |
dict[str, float]
|
|
dict[str, float]
|
|
Example
metrics = RunMetrics(episodes=[...]) stats = metrics.summary_statistics() print(f"Mean VFE: {stats['mean_free_energy_mean']:.4f}")
Source code in py/cogant/runtime/metrics.py
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 | |
free_energy(state_dist, obs_idx, A, C, D)
Evaluate posterior VFE against the supplied current predicted prior D.
Source code in py/cogant/runtime/metrics.py
22 23 24 25 26 27 28 29 30 31 32 33 | |
kl_divergence(p, q)
Return exact categorical KL, including infinite support mismatch.
Source code in py/cogant/runtime/metrics.py
17 18 19 | |
Examples
AgentRuntime, AgentConfig, the run_n_steps / run_until_convergence / run_multi_episode drivers, and the free-energy / KL helpers are exercised by:
- Zoo:
examples/zoo/04_pomdp_minimal/— minimal POMDP that the runtime loop can drive end-to-end. - Zoo:
examples/zoo/09_policy/— policy + action selection target forrun_until_convergence. - Zoo:
examples/zoo/12_full_pomdp/— the canonical multi-episode learning target forrun_multi_episode. - Cookbook: Recipe 17: Benchmarking the runtime — wall-clock characterization of the loop.
- Tutorial: Tutorial 6: Reverse mode — GNN to code — runs the synthesized package under
AgentRuntimeafter reverse synthesis.