Skip to content

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
@dataclass
class AgentConfig:
    """Configuration for the Active Inference agent loop.

    Attributes:
        max_steps: Maximum number of inference steps before forced halt.
            Must be non-negative.
        convergence_threshold: KL divergence threshold below which the
            agent considers its belief to have converged. Must be in (0, 1).
    """

    max_steps: int = 100
    convergence_threshold: float = 1e-4

    def __post_init__(self) -> None:
        """Validate configuration after initialization.

        Raises:
            ValueError: If any configuration value is invalid.
        """
        if type(self.max_steps) is not int or self.max_steps < 0:
            raise ValueError(f"max_steps must be a non-negative integer; got {self.max_steps}")

        if (
            isinstance(self.convergence_threshold, bool)
            or not isinstance(self.convergence_threshold, (int, float))
            or not math.isfinite(self.convergence_threshold)
            or not (0 < self.convergence_threshold < 1)
        ):
            raise ValueError(
                f"convergence_threshold must be in (0, 1); got {self.convergence_threshold}"
            )

    @classmethod
    def from_yaml(cls, path: str) -> AgentConfig:
        """Load configuration from a YAML file.

        Args:
            path: Path to YAML file with keys matching AgentConfig fields.

        Returns:
            Loaded AgentConfig instance.

        Raises:
            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")
        """
        try:
            import yaml
        except ImportError as exc:
            raise ImportError(
                "pyyaml is required for from_yaml(); install it with: pip install pyyaml"
            ) from exc

        with open(path, encoding="utf-8") as f:
            data = yaml.safe_load(f)
        if data is None:
            data = {}
        if not isinstance(data, dict):
            raise ValueError("runtime configuration must be a YAML mapping")
        unknown = set(data) - {"max_steps", "convergence_threshold"}
        if unknown:
            raise ValueError(f"unknown runtime configuration fields: {sorted(map(str, unknown))}")
        return cls(**data)

    def to_yaml(self, path: str) -> None:
        """Save configuration to a YAML file.

        Args:
            path: Path where YAML file will be written.

        Raises:
            ImportError: If pyyaml is not installed.

        Example:
            >>> cfg = AgentConfig(max_steps=200)
            >>> cfg.to_yaml("config.yaml")
        """
        try:
            import yaml
        except ImportError as exc:
            raise ImportError(
                "pyyaml is required for to_yaml(); install it with: pip install pyyaml"
            ) from exc

        data = {
            "max_steps": self.max_steps,
            "convergence_threshold": self.convergence_threshold,
        }

        with open(path, "w", encoding="utf-8") as f:
            yaml.safe_dump(data, f, default_flow_style=False)

        logger.info(f"Saved AgentConfig to {path}")

    @classmethod
    def with_defaults(cls) -> AgentConfig:
        """Create a new AgentConfig with sensible defaults.

        Returns:
            A new AgentConfig instance with default values.

        Example:
            >>> cfg = AgentConfig.with_defaults()
            >>> print(cfg.max_steps)
            100
        """
        return cls()

__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
def __post_init__(self) -> None:
    """Validate configuration after initialization.

    Raises:
        ValueError: If any configuration value is invalid.
    """
    if type(self.max_steps) is not int or self.max_steps < 0:
        raise ValueError(f"max_steps must be a non-negative integer; got {self.max_steps}")

    if (
        isinstance(self.convergence_threshold, bool)
        or not isinstance(self.convergence_threshold, (int, float))
        or not math.isfinite(self.convergence_threshold)
        or not (0 < self.convergence_threshold < 1)
    ):
        raise ValueError(
            f"convergence_threshold must be in (0, 1); got {self.convergence_threshold}"
        )

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
@classmethod
def from_yaml(cls, path: str) -> AgentConfig:
    """Load configuration from a YAML file.

    Args:
        path: Path to YAML file with keys matching AgentConfig fields.

    Returns:
        Loaded AgentConfig instance.

    Raises:
        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")
    """
    try:
        import yaml
    except ImportError as exc:
        raise ImportError(
            "pyyaml is required for from_yaml(); install it with: pip install pyyaml"
        ) from exc

    with open(path, encoding="utf-8") as f:
        data = yaml.safe_load(f)
    if data is None:
        data = {}
    if not isinstance(data, dict):
        raise ValueError("runtime configuration must be a YAML mapping")
    unknown = set(data) - {"max_steps", "convergence_threshold"}
    if unknown:
        raise ValueError(f"unknown runtime configuration fields: {sorted(map(str, unknown))}")
    return cls(**data)

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
def to_yaml(self, path: str) -> None:
    """Save configuration to a YAML file.

    Args:
        path: Path where YAML file will be written.

    Raises:
        ImportError: If pyyaml is not installed.

    Example:
        >>> cfg = AgentConfig(max_steps=200)
        >>> cfg.to_yaml("config.yaml")
    """
    try:
        import yaml
    except ImportError as exc:
        raise ImportError(
            "pyyaml is required for to_yaml(); install it with: pip install pyyaml"
        ) from exc

    data = {
        "max_steps": self.max_steps,
        "convergence_threshold": self.convergence_threshold,
    }

    with open(path, "w", encoding="utf-8") as f:
        yaml.safe_dump(data, f, default_flow_style=False)

    logger.info(f"Saved AgentConfig to {path}")

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
@classmethod
def with_defaults(cls) -> AgentConfig:
    """Create a new AgentConfig with sensible defaults.

    Returns:
        A new AgentConfig instance with default values.

    Example:
        >>> cfg = AgentConfig.with_defaults()
        >>> print(cfg.max_steps)
        100
    """
    return cls()

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
class AgentRuntime:
    """Mutable agent matrices with shared categorical inference and learning."""

    def __init__(self, matrices: Any) -> None:
        self.A: list[list[float]] = matrices.A
        self.B: list[list[list[float]]] = matrices.B
        self.C: list[float] = matrices.C
        self.D: list[float] = matrices.D
        self._model = CategoricalModel(self.A, self.B, self.C, self.D)
        self._likelihood = self._model.observe
        self._transition = self._model.predict
        self._n_states = len(self.D)
        self._n_obs = len(self.A)
        self._n_actions = self._model.n_actions
        self._episode_count = 0
        self._last_free_energy = float("nan")

    @classmethod
    def from_matrices_dict(cls, d: dict[str, Any]) -> AgentRuntime:
        return cls(types.SimpleNamespace(A=d["A"], B=d["B"], C=d["C"], D=d["D"]))

    def step(self, state_dist: list[float], obs_idx: int, t: int = 0) -> AgentStep:
        """Filter then choose minimum one-step EFE, with lowest-index ties."""
        result = self._model.step(state_dist, obs_idx)
        self._last_free_energy = result.free_energy
        return AgentStep(
            t,
            result.prediction,
            obs_idx,
            result.action,
            result.free_energy,
            result.posterior,
            result.policy_scores,
        )

    def run_n_steps(self, n: int, initial_state: list[float] | None = None) -> list[AgentStep]:
        """Run a deterministic model rollout using modal predicted observations."""
        if n < 0:
            raise ValueError("step count must be non-negative")
        state = list(self.D if initial_state is None else initial_state)
        distribution(state)
        steps = []
        for t in range(n):
            result = self.step(state, _argmax(self._likelihood(state)), t)
            steps.append(result)
            state = result.state_dist
        return steps

    def run_until_convergence(
        self, initial_state: list[float] | None = None, cfg: AgentConfig | None = None
    ) -> list[AgentStep]:
        cfg = cfg if cfg is not None else AgentConfig()
        state = list(self.D if initial_state is None else initial_state)
        distribution(state)
        steps = []
        for t in range(cfg.max_steps):
            result = self.step(state, _argmax(self._likelihood(state)), t)
            steps.append(result)
            if t > 0 and kl_divergence(result.state_dist, state) < cfg.convergence_threshold:
                break
            state = result.state_dist
        return steps

    def run_episode(self, n_steps: int, initial_state: list[float] | None = None) -> EpisodeResult:
        initial = list(self.D if initial_state is None else initial_state)
        return summarize_episode(self.run_n_steps(n_steps, initial), initial, self._n_obs)

    def update_D_from_posterior(self, posterior: list[float]) -> list[float]:
        if len(posterior) != self._n_states:
            raise ValueError("posterior has incompatible state dimensions")
        normalized = _normalize(posterior)
        k = self._episode_count
        self.D[:] = [(d * k + q) / (k + 1) for d, q in zip(self.D, normalized, strict=True)]
        self._episode_count += 1
        return self.D

    def update_A_from_counts(
        self, obs_state_counts: list[list[float]], learning_rate: float = 0.1
    ) -> list[list[float]]:
        """Blend conditional P(observation | state) counts, leaving unseen states unchanged."""
        if not math.isfinite(learning_rate) or not 0 <= learning_rate <= 1:
            raise ValueError("learning_rate must be finite and in [0, 1]")
        if len(obs_state_counts) != self._n_obs or any(
            len(row) != self._n_states for row in obs_state_counts
        ):
            raise ValueError("observation-state counts have incompatible dimensions")
        if any(not math.isfinite(v) or v < 0 for row in obs_state_counts for v in row):
            raise ValueError("observation-state counts must be finite and non-negative")
        for s in range(self._n_states):
            total = math.fsum(row[s] for row in obs_state_counts)
            if total > 0:
                for o in range(self._n_obs):
                    self.A[o][s] = (1 - learning_rate) * self.A[o][
                        s
                    ] + learning_rate * obs_state_counts[o][s] / total
        return self.A

    def run_multi_episode(
        self,
        n_episodes: int,
        steps_per_episode: int,
        learning_rate: float = 0.1,
        initial_state: list[float] | None = None,
    ) -> MultiEpisodeResult:
        if n_episodes < 0:
            raise ValueError("episode count must be non-negative")
        episodes = []
        priors = []
        for _ in range(n_episodes):
            result = self.run_episode(steps_per_episode, initial_state)
            episodes.append(result)
            self.update_D_from_posterior(result.final_posterior)
            self.update_A_from_counts(result.obs_state_counts, learning_rate)
            priors.append(list(self.D))
        return MultiEpisodeResult(
            episodes,
            [e.mean_free_energy for e in episodes],
            [e.final_free_energy for e in episodes],
            priors,
            learning_rate,
        )

    def run_episode_with_logging(
        self, obs_sequence: list[int]
    ) -> tuple[EpisodeResult, list[dict[str, Any]]]:
        state = list(self.D)
        steps = []
        logs = []
        for t, obs in enumerate(obs_sequence):
            result = self.step(state, obs, t)
            steps.append(result)
            logs.append(
                {
                    "step": t,
                    "observation": obs,
                    "action": result.action,
                    "free_energy": result.free_energy,
                }
            )
            state = result.state_dist
        return summarize_episode(steps, self.D, self._n_obs), logs

    def benchmark(self, n_episodes: int = 10) -> dict[str, float]:
        if n_episodes <= 0:
            raise ValueError("benchmark episode count must be positive")
        elapsed = []
        for _ in range(n_episodes):
            start = time.perf_counter()
            self.run_episode(5)
            elapsed.append((time.perf_counter() - start) * 1000)
        mean = sum(elapsed) / len(elapsed)
        return {
            "mean_ms": mean,
            "std_ms": (sum((x - mean) ** 2 for x in elapsed) / len(elapsed)) ** 0.5,
            "min_ms": min(elapsed),
            "max_ms": max(elapsed),
        }

    def reset(self) -> None:
        self._episode_count = 0
        self._last_free_energy = float("nan")

    def get_free_energy(self) -> float:
        return self._last_free_energy

    def to_dict(self) -> dict[str, Any]:
        return {
            "A": self.A,
            "B": self.B,
            "C": self.C,
            "D": self.D,
            "n_states": self._n_states,
            "n_obs": self._n_obs,
            "n_actions": self._n_actions,
            "episode_count": self._episode_count,
        }

    @classmethod
    def from_dict(cls, d: dict[str, Any]) -> AgentRuntime:
        runtime = cls.from_matrices_dict(d)
        runtime._episode_count = d.get("episode_count", 0)
        return runtime

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
def step(self, state_dist: list[float], obs_idx: int, t: int = 0) -> AgentStep:
    """Filter then choose minimum one-step EFE, with lowest-index ties."""
    result = self._model.step(state_dist, obs_idx)
    self._last_free_energy = result.free_energy
    return AgentStep(
        t,
        result.prediction,
        obs_idx,
        result.action,
        result.free_energy,
        result.posterior,
        result.policy_scores,
    )

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
def run_n_steps(self, n: int, initial_state: list[float] | None = None) -> list[AgentStep]:
    """Run a deterministic model rollout using modal predicted observations."""
    if n < 0:
        raise ValueError("step count must be non-negative")
    state = list(self.D if initial_state is None else initial_state)
    distribution(state)
    steps = []
    for t in range(n):
        result = self.step(state, _argmax(self._likelihood(state)), t)
        steps.append(result)
        state = result.state_dist
    return steps

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
def update_A_from_counts(
    self, obs_state_counts: list[list[float]], learning_rate: float = 0.1
) -> list[list[float]]:
    """Blend conditional P(observation | state) counts, leaving unseen states unchanged."""
    if not math.isfinite(learning_rate) or not 0 <= learning_rate <= 1:
        raise ValueError("learning_rate must be finite and in [0, 1]")
    if len(obs_state_counts) != self._n_obs or any(
        len(row) != self._n_states for row in obs_state_counts
    ):
        raise ValueError("observation-state counts have incompatible dimensions")
    if any(not math.isfinite(v) or v < 0 for row in obs_state_counts for v in row):
        raise ValueError("observation-state counts must be finite and non-negative")
    for s in range(self._n_states):
        total = math.fsum(row[s] for row in obs_state_counts)
        if total > 0:
            for o in range(self._n_obs):
                self.A[o][s] = (1 - learning_rate) * self.A[o][
                    s
                ] + learning_rate * obs_state_counts[o][s] / total
    return self.A

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
@dataclass(frozen=True, slots=True)
class AgentStep:
    """One cycle: posterior and VFE precede control; state_dist follows control."""

    t: int
    state_dist: list[float]
    obs: int
    action: int
    free_energy: float
    posterior: list[float] = field(default_factory=list)
    policy_scores: list[float] = field(default_factory=list)

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
@dataclass(frozen=True, slots=True)
class EpisodeResult:
    """Observed posterior soft counts and the final corrected posterior."""

    steps: list[AgentStep]
    final_posterior: list[float]
    obs_counts: list[float]
    obs_state_counts: list[list[float]]
    mean_free_energy: float
    final_free_energy: float

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
@dataclass(frozen=True, slots=True)
class MultiEpisodeResult:
    """Episode metrics and learned-prior snapshots."""

    episodes: list[EpisodeResult]
    vfe_trajectory: list[float]
    final_vfe_trajectory: list[float]
    D_trajectory: list[list[float]]
    learning_rate: float

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
@dataclass(frozen=True, slots=True)
class AgentStep:
    """One cycle: posterior and VFE precede control; state_dist follows control."""

    t: int
    state_dist: list[float]
    obs: int
    action: int
    free_energy: float
    posterior: list[float] = field(default_factory=list)
    policy_scores: list[float] = field(default_factory=list)

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
@dataclass(frozen=True, slots=True)
class EpisodeResult:
    """Observed posterior soft counts and the final corrected posterior."""

    steps: list[AgentStep]
    final_posterior: list[float]
    obs_counts: list[float]
    obs_state_counts: list[list[float]]
    mean_free_energy: float
    final_free_energy: float

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
@dataclass(frozen=True, slots=True)
class MultiEpisodeResult:
    """Episode metrics and learned-prior snapshots."""

    episodes: list[EpisodeResult]
    vfe_trajectory: list[float]
    final_vfe_trajectory: list[float]
    D_trajectory: list[list[float]]
    learning_rate: float

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
class AgentRuntime:
    """Mutable agent matrices with shared categorical inference and learning."""

    def __init__(self, matrices: Any) -> None:
        self.A: list[list[float]] = matrices.A
        self.B: list[list[list[float]]] = matrices.B
        self.C: list[float] = matrices.C
        self.D: list[float] = matrices.D
        self._model = CategoricalModel(self.A, self.B, self.C, self.D)
        self._likelihood = self._model.observe
        self._transition = self._model.predict
        self._n_states = len(self.D)
        self._n_obs = len(self.A)
        self._n_actions = self._model.n_actions
        self._episode_count = 0
        self._last_free_energy = float("nan")

    @classmethod
    def from_matrices_dict(cls, d: dict[str, Any]) -> AgentRuntime:
        return cls(types.SimpleNamespace(A=d["A"], B=d["B"], C=d["C"], D=d["D"]))

    def step(self, state_dist: list[float], obs_idx: int, t: int = 0) -> AgentStep:
        """Filter then choose minimum one-step EFE, with lowest-index ties."""
        result = self._model.step(state_dist, obs_idx)
        self._last_free_energy = result.free_energy
        return AgentStep(
            t,
            result.prediction,
            obs_idx,
            result.action,
            result.free_energy,
            result.posterior,
            result.policy_scores,
        )

    def run_n_steps(self, n: int, initial_state: list[float] | None = None) -> list[AgentStep]:
        """Run a deterministic model rollout using modal predicted observations."""
        if n < 0:
            raise ValueError("step count must be non-negative")
        state = list(self.D if initial_state is None else initial_state)
        distribution(state)
        steps = []
        for t in range(n):
            result = self.step(state, _argmax(self._likelihood(state)), t)
            steps.append(result)
            state = result.state_dist
        return steps

    def run_until_convergence(
        self, initial_state: list[float] | None = None, cfg: AgentConfig | None = None
    ) -> list[AgentStep]:
        cfg = cfg if cfg is not None else AgentConfig()
        state = list(self.D if initial_state is None else initial_state)
        distribution(state)
        steps = []
        for t in range(cfg.max_steps):
            result = self.step(state, _argmax(self._likelihood(state)), t)
            steps.append(result)
            if t > 0 and kl_divergence(result.state_dist, state) < cfg.convergence_threshold:
                break
            state = result.state_dist
        return steps

    def run_episode(self, n_steps: int, initial_state: list[float] | None = None) -> EpisodeResult:
        initial = list(self.D if initial_state is None else initial_state)
        return summarize_episode(self.run_n_steps(n_steps, initial), initial, self._n_obs)

    def update_D_from_posterior(self, posterior: list[float]) -> list[float]:
        if len(posterior) != self._n_states:
            raise ValueError("posterior has incompatible state dimensions")
        normalized = _normalize(posterior)
        k = self._episode_count
        self.D[:] = [(d * k + q) / (k + 1) for d, q in zip(self.D, normalized, strict=True)]
        self._episode_count += 1
        return self.D

    def update_A_from_counts(
        self, obs_state_counts: list[list[float]], learning_rate: float = 0.1
    ) -> list[list[float]]:
        """Blend conditional P(observation | state) counts, leaving unseen states unchanged."""
        if not math.isfinite(learning_rate) or not 0 <= learning_rate <= 1:
            raise ValueError("learning_rate must be finite and in [0, 1]")
        if len(obs_state_counts) != self._n_obs or any(
            len(row) != self._n_states for row in obs_state_counts
        ):
            raise ValueError("observation-state counts have incompatible dimensions")
        if any(not math.isfinite(v) or v < 0 for row in obs_state_counts for v in row):
            raise ValueError("observation-state counts must be finite and non-negative")
        for s in range(self._n_states):
            total = math.fsum(row[s] for row in obs_state_counts)
            if total > 0:
                for o in range(self._n_obs):
                    self.A[o][s] = (1 - learning_rate) * self.A[o][
                        s
                    ] + learning_rate * obs_state_counts[o][s] / total
        return self.A

    def run_multi_episode(
        self,
        n_episodes: int,
        steps_per_episode: int,
        learning_rate: float = 0.1,
        initial_state: list[float] | None = None,
    ) -> MultiEpisodeResult:
        if n_episodes < 0:
            raise ValueError("episode count must be non-negative")
        episodes = []
        priors = []
        for _ in range(n_episodes):
            result = self.run_episode(steps_per_episode, initial_state)
            episodes.append(result)
            self.update_D_from_posterior(result.final_posterior)
            self.update_A_from_counts(result.obs_state_counts, learning_rate)
            priors.append(list(self.D))
        return MultiEpisodeResult(
            episodes,
            [e.mean_free_energy for e in episodes],
            [e.final_free_energy for e in episodes],
            priors,
            learning_rate,
        )

    def run_episode_with_logging(
        self, obs_sequence: list[int]
    ) -> tuple[EpisodeResult, list[dict[str, Any]]]:
        state = list(self.D)
        steps = []
        logs = []
        for t, obs in enumerate(obs_sequence):
            result = self.step(state, obs, t)
            steps.append(result)
            logs.append(
                {
                    "step": t,
                    "observation": obs,
                    "action": result.action,
                    "free_energy": result.free_energy,
                }
            )
            state = result.state_dist
        return summarize_episode(steps, self.D, self._n_obs), logs

    def benchmark(self, n_episodes: int = 10) -> dict[str, float]:
        if n_episodes <= 0:
            raise ValueError("benchmark episode count must be positive")
        elapsed = []
        for _ in range(n_episodes):
            start = time.perf_counter()
            self.run_episode(5)
            elapsed.append((time.perf_counter() - start) * 1000)
        mean = sum(elapsed) / len(elapsed)
        return {
            "mean_ms": mean,
            "std_ms": (sum((x - mean) ** 2 for x in elapsed) / len(elapsed)) ** 0.5,
            "min_ms": min(elapsed),
            "max_ms": max(elapsed),
        }

    def reset(self) -> None:
        self._episode_count = 0
        self._last_free_energy = float("nan")

    def get_free_energy(self) -> float:
        return self._last_free_energy

    def to_dict(self) -> dict[str, Any]:
        return {
            "A": self.A,
            "B": self.B,
            "C": self.C,
            "D": self.D,
            "n_states": self._n_states,
            "n_obs": self._n_obs,
            "n_actions": self._n_actions,
            "episode_count": self._episode_count,
        }

    @classmethod
    def from_dict(cls, d: dict[str, Any]) -> AgentRuntime:
        runtime = cls.from_matrices_dict(d)
        runtime._episode_count = d.get("episode_count", 0)
        return runtime

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
def step(self, state_dist: list[float], obs_idx: int, t: int = 0) -> AgentStep:
    """Filter then choose minimum one-step EFE, with lowest-index ties."""
    result = self._model.step(state_dist, obs_idx)
    self._last_free_energy = result.free_energy
    return AgentStep(
        t,
        result.prediction,
        obs_idx,
        result.action,
        result.free_energy,
        result.posterior,
        result.policy_scores,
    )

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
def run_n_steps(self, n: int, initial_state: list[float] | None = None) -> list[AgentStep]:
    """Run a deterministic model rollout using modal predicted observations."""
    if n < 0:
        raise ValueError("step count must be non-negative")
    state = list(self.D if initial_state is None else initial_state)
    distribution(state)
    steps = []
    for t in range(n):
        result = self.step(state, _argmax(self._likelihood(state)), t)
        steps.append(result)
        state = result.state_dist
    return steps

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
def update_A_from_counts(
    self, obs_state_counts: list[list[float]], learning_rate: float = 0.1
) -> list[list[float]]:
    """Blend conditional P(observation | state) counts, leaving unseen states unchanged."""
    if not math.isfinite(learning_rate) or not 0 <= learning_rate <= 1:
        raise ValueError("learning_rate must be finite and in [0, 1]")
    if len(obs_state_counts) != self._n_obs or any(
        len(row) != self._n_states for row in obs_state_counts
    ):
        raise ValueError("observation-state counts have incompatible dimensions")
    if any(not math.isfinite(v) or v < 0 for row in obs_state_counts for v in row):
        raise ValueError("observation-state counts must be finite and non-negative")
    for s in range(self._n_states):
        total = math.fsum(row[s] for row in obs_state_counts)
        if total > 0:
            for o in range(self._n_obs):
                self.A[o][s] = (1 - learning_rate) * self.A[o][
                    s
                ] + learning_rate * obs_state_counts[o][s] / total
    return self.A

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
@dataclass
class AgentConfig:
    """Configuration for the Active Inference agent loop.

    Attributes:
        max_steps: Maximum number of inference steps before forced halt.
            Must be non-negative.
        convergence_threshold: KL divergence threshold below which the
            agent considers its belief to have converged. Must be in (0, 1).
    """

    max_steps: int = 100
    convergence_threshold: float = 1e-4

    def __post_init__(self) -> None:
        """Validate configuration after initialization.

        Raises:
            ValueError: If any configuration value is invalid.
        """
        if type(self.max_steps) is not int or self.max_steps < 0:
            raise ValueError(f"max_steps must be a non-negative integer; got {self.max_steps}")

        if (
            isinstance(self.convergence_threshold, bool)
            or not isinstance(self.convergence_threshold, (int, float))
            or not math.isfinite(self.convergence_threshold)
            or not (0 < self.convergence_threshold < 1)
        ):
            raise ValueError(
                f"convergence_threshold must be in (0, 1); got {self.convergence_threshold}"
            )

    @classmethod
    def from_yaml(cls, path: str) -> AgentConfig:
        """Load configuration from a YAML file.

        Args:
            path: Path to YAML file with keys matching AgentConfig fields.

        Returns:
            Loaded AgentConfig instance.

        Raises:
            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")
        """
        try:
            import yaml
        except ImportError as exc:
            raise ImportError(
                "pyyaml is required for from_yaml(); install it with: pip install pyyaml"
            ) from exc

        with open(path, encoding="utf-8") as f:
            data = yaml.safe_load(f)
        if data is None:
            data = {}
        if not isinstance(data, dict):
            raise ValueError("runtime configuration must be a YAML mapping")
        unknown = set(data) - {"max_steps", "convergence_threshold"}
        if unknown:
            raise ValueError(f"unknown runtime configuration fields: {sorted(map(str, unknown))}")
        return cls(**data)

    def to_yaml(self, path: str) -> None:
        """Save configuration to a YAML file.

        Args:
            path: Path where YAML file will be written.

        Raises:
            ImportError: If pyyaml is not installed.

        Example:
            >>> cfg = AgentConfig(max_steps=200)
            >>> cfg.to_yaml("config.yaml")
        """
        try:
            import yaml
        except ImportError as exc:
            raise ImportError(
                "pyyaml is required for to_yaml(); install it with: pip install pyyaml"
            ) from exc

        data = {
            "max_steps": self.max_steps,
            "convergence_threshold": self.convergence_threshold,
        }

        with open(path, "w", encoding="utf-8") as f:
            yaml.safe_dump(data, f, default_flow_style=False)

        logger.info(f"Saved AgentConfig to {path}")

    @classmethod
    def with_defaults(cls) -> AgentConfig:
        """Create a new AgentConfig with sensible defaults.

        Returns:
            A new AgentConfig instance with default values.

        Example:
            >>> cfg = AgentConfig.with_defaults()
            >>> print(cfg.max_steps)
            100
        """
        return cls()

__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
def __post_init__(self) -> None:
    """Validate configuration after initialization.

    Raises:
        ValueError: If any configuration value is invalid.
    """
    if type(self.max_steps) is not int or self.max_steps < 0:
        raise ValueError(f"max_steps must be a non-negative integer; got {self.max_steps}")

    if (
        isinstance(self.convergence_threshold, bool)
        or not isinstance(self.convergence_threshold, (int, float))
        or not math.isfinite(self.convergence_threshold)
        or not (0 < self.convergence_threshold < 1)
    ):
        raise ValueError(
            f"convergence_threshold must be in (0, 1); got {self.convergence_threshold}"
        )

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
@classmethod
def from_yaml(cls, path: str) -> AgentConfig:
    """Load configuration from a YAML file.

    Args:
        path: Path to YAML file with keys matching AgentConfig fields.

    Returns:
        Loaded AgentConfig instance.

    Raises:
        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")
    """
    try:
        import yaml
    except ImportError as exc:
        raise ImportError(
            "pyyaml is required for from_yaml(); install it with: pip install pyyaml"
        ) from exc

    with open(path, encoding="utf-8") as f:
        data = yaml.safe_load(f)
    if data is None:
        data = {}
    if not isinstance(data, dict):
        raise ValueError("runtime configuration must be a YAML mapping")
    unknown = set(data) - {"max_steps", "convergence_threshold"}
    if unknown:
        raise ValueError(f"unknown runtime configuration fields: {sorted(map(str, unknown))}")
    return cls(**data)

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
def to_yaml(self, path: str) -> None:
    """Save configuration to a YAML file.

    Args:
        path: Path where YAML file will be written.

    Raises:
        ImportError: If pyyaml is not installed.

    Example:
        >>> cfg = AgentConfig(max_steps=200)
        >>> cfg.to_yaml("config.yaml")
    """
    try:
        import yaml
    except ImportError as exc:
        raise ImportError(
            "pyyaml is required for to_yaml(); install it with: pip install pyyaml"
        ) from exc

    data = {
        "max_steps": self.max_steps,
        "convergence_threshold": self.convergence_threshold,
    }

    with open(path, "w", encoding="utf-8") as f:
        yaml.safe_dump(data, f, default_flow_style=False)

    logger.info(f"Saved AgentConfig to {path}")

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
@classmethod
def with_defaults(cls) -> AgentConfig:
    """Create a new AgentConfig with sensible defaults.

    Returns:
        A new AgentConfig instance with default values.

    Example:
        >>> cfg = AgentConfig.with_defaults()
        >>> print(cfg.max_steps)
        100
    """
    return cls()

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
@dataclass
class EpisodeMetrics:
    """Metrics for a single learning episode.

    Attributes:
        episode_id: Unique episode identifier.
        n_steps: Number of steps in the episode.
        mean_free_energy: Mean VFE across the episode.
        final_free_energy: VFE at the last step.
        n_unique_obs: Number of unique observations seen.
        action_entropy: Shannon entropy of action distribution.
    """

    episode_id: int
    n_steps: int
    mean_free_energy: float
    final_free_energy: float
    n_unique_obs: int = 0
    action_entropy: float = 0.0

    def to_csv_row(self) -> dict[str, Any]:
        """Convert metrics to a dictionary suitable for CSV logging.

        Returns:
            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)
        """
        return {
            "episode_id": self.episode_id,
            "n_steps": self.n_steps,
            "mean_free_energy": self.mean_free_energy,
            "final_free_energy": self.final_free_energy,
            "n_unique_obs": self.n_unique_obs,
            "action_entropy": self.action_entropy,
        }

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
def to_csv_row(self) -> dict[str, Any]:
    """Convert metrics to a dictionary suitable for CSV logging.

    Returns:
        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)
    """
    return {
        "episode_id": self.episode_id,
        "n_steps": self.n_steps,
        "mean_free_energy": self.mean_free_energy,
        "final_free_energy": self.final_free_energy,
        "n_unique_obs": self.n_unique_obs,
        "action_entropy": self.action_entropy,
    }

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
@dataclass
class RunMetrics:
    """Aggregate metrics for a multi-episode learning run.

    Attributes:
        episodes: List of per-episode metrics.
        total_steps: Total inference steps across all episodes.
    """

    episodes: list[EpisodeMetrics]
    total_steps: int = 0

    def summary_statistics(self) -> dict[str, float]:
        """Compute summary statistics over all episodes.

        Returns:
            Dictionary with mean/std/min/max for:
            * ``mean_free_energy_mean``, ``mean_free_energy_std``, etc.
            * ``final_free_energy_mean``, ``final_free_energy_std``, etc.

        Example:
            >>> metrics = RunMetrics(episodes=[...])
            >>> stats = metrics.summary_statistics()
            >>> print(f"Mean VFE: {stats['mean_free_energy_mean']:.4f}")
        """
        if not self.episodes:
            logger.warning("No episodes in RunMetrics; returning NaN-filled stats")
            nan = float("nan")
            return {
                "n_episodes": 0,
                "total_steps": 0,
                "mean_free_energy_mean": nan,
                "mean_free_energy_std": nan,
                "mean_free_energy_min": nan,
                "mean_free_energy_max": nan,
                "final_free_energy_mean": nan,
                "final_free_energy_std": nan,
                "final_free_energy_min": nan,
                "final_free_energy_max": nan,
                "steps_per_episode_mean": nan,
                "steps_per_episode_std": nan,
            }

        mean_fes = [e.mean_free_energy for e in self.episodes]
        final_fes = [e.final_free_energy for e in self.episodes]
        step_counts = [e.n_steps for e in self.episodes]

        def _stats(values: list[float]) -> tuple[float, float, float, float]:
            """Compute mean, std, min, max."""
            if not values:
                return 0.0, 0.0, 0.0, 0.0
            mean = sum(values) / len(values)
            variance = sum((v - mean) ** 2 for v in values) / len(values)
            std = variance**0.5
            return mean, std, min(values), max(values)

        mean_fe_mean, mean_fe_std, mean_fe_min, mean_fe_max = _stats(mean_fes)
        final_fe_mean, final_fe_std, final_fe_min, final_fe_max = _stats(final_fes)
        step_mean, step_std, step_min, step_max = _stats([float(s) for s in step_counts])

        return {
            "n_episodes": len(self.episodes),
            "total_steps": sum(step_counts),
            "mean_free_energy_mean": mean_fe_mean,
            "mean_free_energy_std": mean_fe_std,
            "mean_free_energy_min": mean_fe_min,
            "mean_free_energy_max": mean_fe_max,
            "final_free_energy_mean": final_fe_mean,
            "final_free_energy_std": final_fe_std,
            "final_free_energy_min": final_fe_min,
            "final_free_energy_max": final_fe_max,
            "steps_per_episode_mean": step_mean,
            "steps_per_episode_std": step_std,
        }

    def plot_free_energy(self) -> Any:
        """Plot mean and final VFE trajectories (if matplotlib available).

        Returns:
            A matplotlib Figure object if matplotlib is installed and there
            are episodes to plot; None otherwise.

        Example:
            >>> metrics = RunMetrics(episodes=[...])
            >>> fig = metrics.plot_free_energy()
            >>> if fig:
            ...     fig.show()
        """
        if not self.episodes:
            logger.warning("No episodes to plot")
            return None

        try:
            import matplotlib.pyplot as plt
        except ImportError:
            logger.warning("matplotlib not available; skipping plot_free_energy()")
            return None

        episode_ids = list(range(len(self.episodes)))
        mean_fes = [e.mean_free_energy for e in self.episodes]
        final_fes = [e.final_free_energy for e in self.episodes]

        fig, ax = plt.subplots(figsize=(10, 6))
        ax.plot(episode_ids, mean_fes, "b-o", label="Mean VFE", linewidth=2)
        ax.plot(episode_ids, final_fes, "r--s", label="Final VFE", linewidth=2)
        ax.set_xlabel("Episode", fontsize=12)
        ax.set_ylabel("Free Energy", fontsize=12)
        ax.set_title("VFE Trajectory Over Episodes", fontsize=14)
        ax.legend(fontsize=11)
        ax.grid(True, alpha=0.3)

        return fig

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
def plot_free_energy(self) -> Any:
    """Plot mean and final VFE trajectories (if matplotlib available).

    Returns:
        A matplotlib Figure object if matplotlib is installed and there
        are episodes to plot; None otherwise.

    Example:
        >>> metrics = RunMetrics(episodes=[...])
        >>> fig = metrics.plot_free_energy()
        >>> if fig:
        ...     fig.show()
    """
    if not self.episodes:
        logger.warning("No episodes to plot")
        return None

    try:
        import matplotlib.pyplot as plt
    except ImportError:
        logger.warning("matplotlib not available; skipping plot_free_energy()")
        return None

    episode_ids = list(range(len(self.episodes)))
    mean_fes = [e.mean_free_energy for e in self.episodes]
    final_fes = [e.final_free_energy for e in self.episodes]

    fig, ax = plt.subplots(figsize=(10, 6))
    ax.plot(episode_ids, mean_fes, "b-o", label="Mean VFE", linewidth=2)
    ax.plot(episode_ids, final_fes, "r--s", label="Final VFE", linewidth=2)
    ax.set_xlabel("Episode", fontsize=12)
    ax.set_ylabel("Free Energy", fontsize=12)
    ax.set_title("VFE Trajectory Over Episodes", fontsize=14)
    ax.legend(fontsize=11)
    ax.grid(True, alpha=0.3)

    return fig

summary_statistics()

Compute summary statistics over all episodes.

Returns:

Type Description
dict[str, float]

Dictionary with mean/std/min/max for:

dict[str, float]
  • mean_free_energy_mean, mean_free_energy_std, etc.
dict[str, float]
  • final_free_energy_mean, final_free_energy_std, etc.
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
def summary_statistics(self) -> dict[str, float]:
    """Compute summary statistics over all episodes.

    Returns:
        Dictionary with mean/std/min/max for:
        * ``mean_free_energy_mean``, ``mean_free_energy_std``, etc.
        * ``final_free_energy_mean``, ``final_free_energy_std``, etc.

    Example:
        >>> metrics = RunMetrics(episodes=[...])
        >>> stats = metrics.summary_statistics()
        >>> print(f"Mean VFE: {stats['mean_free_energy_mean']:.4f}")
    """
    if not self.episodes:
        logger.warning("No episodes in RunMetrics; returning NaN-filled stats")
        nan = float("nan")
        return {
            "n_episodes": 0,
            "total_steps": 0,
            "mean_free_energy_mean": nan,
            "mean_free_energy_std": nan,
            "mean_free_energy_min": nan,
            "mean_free_energy_max": nan,
            "final_free_energy_mean": nan,
            "final_free_energy_std": nan,
            "final_free_energy_min": nan,
            "final_free_energy_max": nan,
            "steps_per_episode_mean": nan,
            "steps_per_episode_std": nan,
        }

    mean_fes = [e.mean_free_energy for e in self.episodes]
    final_fes = [e.final_free_energy for e in self.episodes]
    step_counts = [e.n_steps for e in self.episodes]

    def _stats(values: list[float]) -> tuple[float, float, float, float]:
        """Compute mean, std, min, max."""
        if not values:
            return 0.0, 0.0, 0.0, 0.0
        mean = sum(values) / len(values)
        variance = sum((v - mean) ** 2 for v in values) / len(values)
        std = variance**0.5
        return mean, std, min(values), max(values)

    mean_fe_mean, mean_fe_std, mean_fe_min, mean_fe_max = _stats(mean_fes)
    final_fe_mean, final_fe_std, final_fe_min, final_fe_max = _stats(final_fes)
    step_mean, step_std, step_min, step_max = _stats([float(s) for s in step_counts])

    return {
        "n_episodes": len(self.episodes),
        "total_steps": sum(step_counts),
        "mean_free_energy_mean": mean_fe_mean,
        "mean_free_energy_std": mean_fe_std,
        "mean_free_energy_min": mean_fe_min,
        "mean_free_energy_max": mean_fe_max,
        "final_free_energy_mean": final_fe_mean,
        "final_free_energy_std": final_fe_std,
        "final_free_energy_min": final_fe_min,
        "final_free_energy_max": final_fe_max,
        "steps_per_episode_mean": step_mean,
        "steps_per_episode_std": step_std,
    }

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
def free_energy(
    state_dist: list[float],
    obs_idx: int,
    A: list[list[float]],
    C: list[float],
    D: list[float],
) -> float:
    """Evaluate posterior VFE against the supplied current predicted prior D."""
    if not 0 <= obs_idx < len(A):
        raise ValueError("observation index is outside the likelihood axis")
    observation = [float(i == obs_idx) for i in range(len(A))]
    return variational_free_energy(state_dist, D, A, observation)

kl_divergence(p, q)

Return exact categorical KL, including infinite support mismatch.

Source code in py/cogant/runtime/metrics.py
17
18
19
def kl_divergence(p: list[float], q: list[float]) -> float:
    """Return exact categorical KL, including infinite support mismatch."""
    return categorical_kl(p, q)

Examples

AgentRuntime, AgentConfig, the run_n_steps / run_until_convergence / run_multi_episode drivers, and the free-energy / KL helpers are exercised by: