API#
Datasets#
Helpers to load the example datasets shipped with the package.
|
Load dataset for continuous or binary HGF. |
Updates functions#
Update functions are the heart of probabilistic networks as they shape the propagation of beliefs in the neural hierarchy. The library implements the standard variational updates for value and volatility coupling, as described in Weber et al. (2023).
The updates module contains the update functions used during the belief propagation. Update functions are available through three sub-modules, organized according to their functional roles. We usually dissociate the first updates, triggered top-down (from the leaves to the roots of the networks), that are prediction steps and recover the current state of inference. The second updates are the prediction error, signalling the divergence between the prediction and the new observation (for input nodes), or state (for state nodes). Interleaved with these steps are posterior update steps, where a node receives prediction errors from the child nodes and estimates new statistics.
Posterior updates#
Update the sufficient statistics of a state node after receiving prediction errors from children nodes. The prediction errors from all the children below the node should be computed before calling the posterior update step.
Categorical nodes#
|
Update the categorical input node given an array of binary observations. |
Continuous nodes#
|
Update the posterior of a continuous node using the eHGF update. |
Update the posterior of a continuous node using the eHGF update with mean-field. |
Update the posterior of a continuous node with unbounded quadratic approximation. |
|
|
Compute unbounded posterior for a continuous volatility-parent node. |
Continuous mean update without mean-field approximation. |
|
Continuous mean update with mean-field approximation [R4d094550a653-1]. |
Update the precision of a state node using the volatility prediction errors. |
|
Update the precision of a state node using the volatility prediction errors. |
|
Route to the relaxed enhanced-HGF precision or missing-value update. |
|
|
Route to the enhanced-HGF precision update (mean-field) or the missing path. |
|
Compute new precision in the case of observed values. |
|
Compute new precision in the case of observed values. |
|
Enhanced-HGF precision update for observed values (relaxed value coupling). |
|
Enhanced-HGF precision update for observed values (mean-field value coupling). |
|
Compute new precision in the case of missing observations. |
|
Update the posterior of a continuous node using the standard HGF update. |
Update the posterior of a continuous node using the mean-field standard update. |
Exponential family#
Update the hyperparameters of an ef state node using HGF-implied learning rates. |
Prediction steps#
Compute the expectation for future observation given the influence of parent nodes. The prediction step are executed for all nodes, top-down, before any observation.
Binary nodes#
|
Get the new expected mean and precision of a binary state node. |
Continuous nodes#
|
Compute the expected mean of a continuous state node. |
|
Compute the predicted precisions of a continuous state node (no mean-field). |
|
Compute the expected precision of a continuous state node (mean-field). |
|
Update the expected mean and expected precision of a continuous node [Rad74659bc93e-1]. |
Mean-field (v0.2.11) prediction step for a continuous node. |
Dirichlet processes#
|
Prediction of a Dirichlet process node. |
Prediction error steps#
Compute the value and volatility prediction errors of a given node. The prediction error can only be computed after the posterior update (or observation) of a given node.
Binary state nodes#
Compute the value prediction errors and predicted precision of a binary node. |
|
Update the posterior of a binary node given finite precision of the input. |
Categorical state nodes#
Prediction error from a categorical state node. |
Continuous state nodes#
Compute the value prediction error of a state node. |
|
Compute the volatility prediction error of a state node. |
|
|
Store prediction errors in an input node. |
Dirichlet state nodes#
|
Prediction error and update the child networks of a Dirichlet process node. |
|
Update an existing cluster. |
|
Create a new cluster. |
|
Find the best cluster candidate given previous clusters and an input value. |
|
Sample likely new belief distributions given pre-existing clusters. |
|
Likelihood of a parametrised candidate under the new observation. |
Exponential family#
Update the parameters of an exponential family distribution. |
|
Pass the expected sufficient statistics to the implied continuous nodes. |
Observations#
Functions for setting observations on input nodes.
|
Add observations to the target node by setting the posterior to a given value. |
Vectorised updates#
Layer-wise vectorised implementations of the HGF update equations for deep predictive
coding networks. These functions operate on entire layers instead of individual nodes
and are used internally by pyhgf.model.DeepNetwork.
Volatile layers#
|
Predict expected mean/precision for all nodes in a volatile-node layer. |
|
Predict the precisions of a layer that has no value parent above it. |
|
Update the value-level posterior for all nodes in a parent layer. |
Update the precision of the value level for all nodes in a layer. |
|
Update the mean of the value level for all nodes in a layer. |
|
Compute the value prediction error for all nodes in a layer. |
|
Compute the volatility prediction error for all nodes in a layer. |
|
Update the volatility level using the standard ordering. |
|
EHGF volatility-level posterior update (mean first, then safe precision). |
|
Unbounded volatility-level posterior update (Lambert W₀ dual-quadratic). |
|
|
Compute prediction errors and apply the volatility-level posterior update. |
Binary layers#
|
Predict expected mean and precision for a binary state node layer. |
Compute prediction errors for a binary state node layer. |
Categorical layers#
|
Predict a categorical state node layer: one belief per class. |
Compute the prediction error of a categorical state node layer. |
Continuous layers#
|
The value child of a continuous layer, as seen by its posterior update. |
|
The volatility child of a continuous layer, as seen by its posterior update. |
|
Predict expected mean and precisions for a layer of continuous nodes. |
Compute the prediction errors a continuous layer sends to its parents. |
|
Compute the value prediction error for all nodes in a continuous layer. |
|
Compute the volatility prediction error for all nodes in a continuous layer. |
|
Dispatch the continuous posterior update on the layer's children. |
|
Apply the standard HGF posterior update: precision first, then the mean. |
|
Enhanced-HGF posterior update: mean first, then the safe precision. |
|
Unbounded posterior update for a pure volatility-parent layer. |
Vectorised learning#
|
Per-layer weight-learning factors for the vectorised deep network. |
Validate the weight-belief rule's settings and fill in the defaults. |
|
One weight matrix's belief update: new mean, new accumulated precision. |
Model#
The main classes used to create probabilistic networks for binary or continuous inputs.
A predictive coding neural network. |
|
Deep predictive coding network with vectorised operations. |
|
Some weight matrices receive essentially no learning signal. |
|
Add continuous state node(s) to a network. |
|
Add constant-state (bias) node(s) to a network. |
|
Add binary state node(s) to a network. |
|
Add exponential family state node(s) to a network. |
|
Add categorical state node(s) to a network. |
|
Add a Dirichlet Process node to a network. |
|
Transform coupling parameter into tuple of indexes and strenghts. |
|
Update the default node parameters using keywords args and dictonary. |
|
Insert a set of parametrised node in a network. |
Weight transplant#
Converters that build a DeepNetwork reproducing the forward pass
of a trained Equinox module, translating its weights into PyHGF’s layer layout.
|
Build a two-layer network computing exactly |
|
Build a three-layer network computing exactly |
|
Build a two-layer network reproducing a table lookup from one-hot inputs. |
|
Build a shared-kernel network holding a transplanted convolution kernel. |
Declarative construction#
Build a DeepNetwork from serialisable layer configurations, for
configuration-driven experiments and reproducible hyperparameter sweeps.
Configuration for one layer in a DeepNetwork. |
|
Resolve a coupling function name to a callable. |
Mixed pipelines#
Declare models as a tree of parts mixing learning PyHGF networks with frozen calculations. Each part translates prediction errors backward through the tree, so locally-learning networks and fixed operations compose into one model.
Base class for all parts in a mixed pipeline. |
|
A learning part: a PyHGF |
|
A frozen part: a fixed calculation that routes errors but never learns. |
|
A chain of parts: forward in order to predict, in reverse to update. |
|
The shortcut junction: |
|
Build a frozen linear map around an |
|
Build a frozen LayerNorm around an |
|
Build a frozen GELU: the error is multiplied by the slope at the cached input. |
Convolution#
A convolution as a weight-shared linear map over image patches: patch extraction and
pooling are frozen parts, and the single learning part is one small
DeepNetwork applied identically to every patch.
Return the |
|
Build a frozen patch extractor: images in, one row per patch out. |
|
Build a frozen average-pool: block-mean forward, uniform-split backward. |
|
Build a frozen max-pool: block-max forward, winner-take-all backward. |
|
Build a frozen reshape between patch rows and the spatial layout. |
|
Build a frozen flatten, mapping |
|
Build a fresh 2-layer |
|
Assemble one conv layer as a part tree: im2col, shared kernel, GELU, pool. |
Transformer#
A GPT-style Transformer assembled from mixed-pipeline parts, where any slot can hold a frozen calculation or a learning PyHGF network.
Causal multi-head self-attention as a composite pipeline part. |
|
The full Transformer as a mixed pipeline, from token ids to logits. |
|
Assemble a |
Fused pipeline execution#
Run a part tree as a single compiled program per training step: the forward walk, the output error, and every local learning step are staged into one graph with all part state passed explicitly.
Run a part tree, one compiled program per training step. |
|
Per-part step magnitudes after a training step, for rate calibration. |
Plots#
Plotting functionalities to visualise parameters trajectories and correlations after observing new data. We are currently fully supporting Graphviz for network structure and Matplotlib for time series visualisation. NetworkX is also available for some functions.
Matplotlib#
|
Plot the trajectories of the nodes' sufficient statistics and surprise. |
|
Plot the heatmap correlation of the sufficient statistics trajectories. |
|
Plot the trajectory of expected sufficient statistics of a set of nodes. |
|
Plot simulation trajectories for nodes. |
|
Plot layer-wise parameter trajectories of a |
Graphviz#
|
Visualisation of node network using GraphViz. |
|
Visualisation of a fully connected deep network using GraphViz. |
Networkx#
|
Visualisation of node network using NetworkX and pydot layout. |
Response#
A collection of response functions. A response function is simply a callable taking at least the HGF instance as input after observation and returning surprise.
|
Gaussian surprise at the first level of a probabilistic network. |
|
Sum of the Gaussian surprise across the probabilistic network. |
|
Time series of binary surprises for all binary state nodes. |
|
Surprise under the binary softmax model. |
|
Surprise from a binary softmax parametrised by the inverse temperature. |
Utils#
Utilities for manipulating neural networks.
|
Add a value or volatility coupling link between a set of nodes. |
|
Add a new continuous-state parent node to the attributes and edges of a network. |
|
Update the networks parameters after observing new data point(s). |
|
Generate a binary network implied by categorical state(-transition) nodes. |
|
List all possible default inputs nodes. |
|
Generate an update sequence from the network's structure. |
|
Return the branch of a network from a given set of root nodes. |
|
Remove a given node from the network. |
|
Sample a value from the distribution of an input node. |
|
Sample n_predictions forward in generative mode. |
|
Export the nodes trajectories and surprise as a Pandas data frame. |
Weight initialisation#
Initialisation strategies for coupling weight matrices in predictive-coding networks.
|
Xavier / Glorot uniform initialisation. |
|
He / Kaiming normal initialisation. |
|
Orthogonal initialisation. |
|
Sparse initialisation. |
Sampling#
Low-level helpers used when sampling from a network’s generative distribution.
|
Perform a single prediction using the provided RNG key. |
Vectorised belief propagation#
Scan-based belief propagation used internally by pyhgf.model.DeepNetwork.
|
Single propagation step through the network. |
|
Forward-only sweep through the network. |
|
Run |
|
Filter a sequence of observations through a continuous network. |
|
JIT-compiled top-down prediction sweep. |
|
JIT-compiled bottom-up prediction-error + posterior sweep. |
|
JIT-compiled weight-learning phase. |
|
JIT-compiled prediction error at the input (top) layer. |
|
One full local learning step for one sample, as a pure function. |
|
One batch-synchronous learning step over many samples at once. |
|
Add precision increments (see |
|
Forward-only sweep for a batch of samples, compiled once and reused. |
|
Batched forward sweep returning the per-sample swept states. |
Math#
Math functions and probability densities.
The multivariate normal as an exponential family distribution [R2fcf60062970-1]. |
|
|
The univariate normal as an exponential family distribution [Rf25c987ee749-1]. |
|
Density of the Gaussian-predictive distribution. |
|
Gaussian density as defined by mean and precision. |
|
Surprise at a binary outcome. |
|
Surprise at an outcome under a Gaussian prediction. |
|
Compute the Kullback-Leibler divergence between two Dirichlet distributions. |
|
Compute the binary surprise with finite precision. |
|
Compute the sigmoid response function with inverse temperature parameter. |
|
Compute the sigmoid parametrised by \(\phi\) and \(\theta\). |
|
Compute the smoothed rectangular weighting function \(b\). |
Principal branch of the Lambert W function for z >= 0. |
Typing#
Named tuples and PyTree containers describing the structure and state of probabilistic networks.
Network structure#
|
Indexes to a node's value and volatility parents. |
|
Set of update functions to apply to the network. |
Vectorised networks#
|
Per-layer static parameters. |
|
Vectorised per-layer state, as an |
|
One layer of the vectorised deep network. |
|
N identical layers stacked into one PyTree with a leading |
|
Complete vectorised network state. |
|
Combine N identical |