Skip to main content

hgf 0.1.1 copy "hgf: ^0.1.1" to clipboard
hgf: ^0.1.1 copied to clipboard

Hierarchical Gaussian Filter, generalised predictive-coding. Dart pyhgf port.

0.1.1 #

  • Parity with pyhgf cd7e176d (fixtures regenerated):
    • #484: volatility parents enter the predicted volatility at their predicted means under the relaxed updates too. The MGF terms Σ κ²/(2π̂) that #480 added to the relaxed prediction and the eHGF re-prediction are gone.
    • #483: the relaxed posterior conditions each value-coupling edge on its own parent. A child's precision for the edge from parent b is π̄_{a|b} = 1/(1/π̄_a + Σ_{m≠b} (t α_m g'(μ̂_m))²/π̂_m), with its other value parents integrated over their predicted beliefs. This only changes children with several value parents. Network, BatchNetwork and its tangents. New shared_child_* fixtures.
    • #486's default (coupling_moments="taylor") matches up to rounding. The opt-in "exact" moments are not ported yet.

0.1.0 #

  • DpProposals (with dpProposalCount, dpCandidatesKept) is exported, its derived columns (sigma2, logNorm, selfDensity, spread) public: the GPU kernels upload the same proposals.

  • NetworkFixes.categoricalMissing (P12, on by default): an unobserved categorical node keeps its α and records a KL divergence and a surprise of 0. pyhgf makes α ±∞ there (the KL NaN on that trial and the next) and scores the empty cells' binary surprise, which CategoricalSurprise fits counted. Network, BatchNetwork, CategoricalSurprise's gradients; in NetworkFixes.toJson as categorical_missing (a saved network without the key keeps the old behaviour).

  • The relaxed eHGF update always re-predicts with the MGF terms Σ κ²/(2π̂), as pyhgf does since #480 (P1 fixed upstream), so Network.ehgfMgfCorrection, its spec and JSON keys and example/ehgf_mgf_correction.dart are removed (an old "ehgf_mgf_correction" key is ignored on read). Fixtures regenerated at pyhgf 4db3b093.

  • Time step as in pyhgf #478 (0.3.3): an input node is generated by its value parents, not drifted by them, so its predicted mean and the noise prediction error take no Δt; a continuous state child's value messages to its parents take t·α (the drift's Δt), in the precision and mean increments of every scheme (standard, mean-field, eHGF, unbounded). Network, BatchNetwork and its tangents. Only timeSteps ≠ 1 changes results. Fixtures regenerated at pyhgf d9958ece. P21's extra term is now α², was (t α)².

  • Noise parents of continuous input nodes (pyhgf #477): a volatility parent of an input sets the precision of its observation noise, exp(−(ε_u + Σ κ μ̂_q)) (γ = 1), and learns from the noise prediction error (the new UpdateStep.noisePredictionErrorContinuous, from the value parents' posteriors). Noise children take the standard increment under every scheme (inside the unbounded update's effective prior). Inputs carry λ²/π, and an input without noise parent has γ = 0. Network and BatchNetwork (bit for bit, tangents included). Fixtures regenerated at pyhgf 1e6e98d7, with 21 noise_parent_* scenarios.

  • NetworkFixes (Network(fixes:), Network.defaultFixes, -DHGF_UPSTREAM=true): corrections of pyhgf bugs, on by default (recommended), off for parity (none). The first is constantNoiseVariance (P21: pyhgf adds a bias parent's placeholder precision to the noise prediction error). In toJson/fromJson and NetworkSpec ("fixes").

  • gaussianDensity is normalised for every precision (pyhgf #475): the leading factor is √π / √(2π), not π / √(2π). This shifts binarySurpriseFinitePrecision by −½ log π.

  • lambertW0 divides the Halley terms by eʷ (pyhgf #475): finite for every z (it was NaN from ~2.7e151, P2).

  • BatchNetwork.predict(): the prediction sweep alone (with or without tangents), reused by the next step, as Network.predict is; for drawing a choice from the predictions before the observation.

  • dp-state nodes record a surprise (an hgf.dart extension; pyhgf defines none, see docs/upstream P20): NodeField.surprise holds the observation's surprise under the node's Chinese-restaurant-process predictive, −log(Σᵢ nᵢ/(α+N) N(x; μᵢ, σᵢ) + α/(α+N) p₀(x)), with p₀ the base measure's predictive (the mean density of the 20 000 proposals; not the candidate cluster, which is fitted to x and would reward one cluster per observation). Log-space, 0 on a missing observation, in Network and BatchNetwork (bit-identical). DpSurprise sums it over dp inputs; no gradients (the likelihood jumps where an assignment flips). Trajectories.nodeSurprise stays NaN for dp nodes, as in pyhgf.

  • benchmark/bin/dp_cost.dart: ~1 ms per dp element-trial (AOT and JIT).

  • BatchNetwork runs dp-state nodes too (batch/batch_vectors.dart), so it now takes every node kind. Each element has its own α, sensory precision and clusters (getVector reads n, expectedMeans, expectedSigmas, activated), and matches Network bit for bit on the 6 dp fixtures (VM, dart2js, dart2wasm, -O4). DpScratch has per-slot proposal row caches (slots:, dpCandidate(slot:)), one per element of a block. dp networks cap blockSize at the slots that fit in 64 MB (52 with 4 clusters). AOT: 1.18 ms per element-trial vs Network's 1.25–1.29 ms (4 clusters, 32 elements).

  • BatchNetwork runs ef-state and categorical-state nodes (batched kernels in batch/batch_vectors.dart, a per-element vector side store [offset][element], multi-column inputs; getVector). Each element matches Network bit for bit on the 11 ef-state and 7 categorical fixtures (VM, dart2js, dart2wasm, -O4), trial by trial and per element. With tangents, exact gradients through them match finite differences on the 7 categorical and 7 HGF-learning ef-state fixtures. dp-state nodes are still refused.

  • CategoricalSurprise: the surprise of the observations at categorical inputs (the node's surprise, Σ binarySurprise(xₖ, μ̂ₖ) over its categories), batched and differentiable.

  • BatchNetwork.valueParentCount / valueParent: a node's value parents without allocating (for response functions).

  • BatchNetwork data rows are nInputColumns wide (the observed flags stay one per input node), as for Network.

  • CouplingFn.tanh uses Cephes' scheme (a rational approximation below 0.625, 1 − 2/(e^{2|x|}+1) above): within 1.3 ulp of mpmath (was 4.5) and 1.8× faster (one exp instead of an exp and a log).

  • erfc (exported), to ~1e-14 relative: a positive-term series below 1.5 and a continued fraction above. The GELU coupling (CouplingFn.gelu) uses it; it used Abramowitz–Stegun 7.1.26 (rshgf's, up to 5e-5 relative in the tail, R3), so GELU now matches JAX's exact GELU instead of rshgf's.

  • Network.toJson() / Network.fromJson(): an exact copy of a network as JSON (nodes and edges as declared, settings, and every field's initial value, including those changed with setInitial/setInitialVector), for sending a network to a Web Worker or saving it. A rebuilt network filters bit for bit like the original (checked on all 61 fixtures, also with parameters changed after build). Custom couplings are written by name.

  • Exact gradients: BatchNetwork(tangents: k) carries k forward-mode tangents per element through every batched update (predictions, prediction errors, standard / eHGF / unbounded posteriors, relaxed or mean-field, linear or non-linear coupling), seeded with setInitialTangent, setValueCouplingTangent and setVolatilityCouplingTangent, read with getTangent / readTangent. surprise(..., gradient:) returns the gradient of each element's total surprise. Primal values stay bit-identical to a batch without tangents. Directions no seed moves (e.g. a response parameter's) are skipped. Checked against Richardson finite differences on every field of every node of the 37 batchable fixtures (VM, dart2js, dart2wasm).

  • ResponseFunction.batchSurprisePartials / supportsGradients and SurprisePartials: a response function reports ∂surprise/∂belief for the beliefs it reads; implemented by every built-in model. binarySurpriseDerivative.

  • Coupling.d3f (g'''), needed for exact gradients through non-linear value coupling; CustomCoupling(d3g: ...) (optional: central differences of d2g otherwise).

  • sigmoidInverseTemperature computes σ(β · logit x) instead of x^β / (x^β + (1 − x)^β): the same function (agrees to 1e-13 relative, same values at 0 and 1), about 3x faster, which makes BinarySoftmaxInverseTemperature ~25% cheaper per trial in a batch.

  • Read-only graph accessors: Network.valueParentsOf, valueChildrenOf, volatilityParentsOf, volatilityChildrenOf, their coupling strengths (valueParentStrengthsOf, volatilityParentStrengthsOf) and couplingOf, for drawing and inspecting a network.

  • Dirichlet process nodes (NodeKind.dpState, Network.addDpState, and Network.addEfState(valueChildren: [...]) for their clusters): each observation goes to the most likely open cluster or opens a new one, with pyhgf's new-cluster proposals (JAX's threefry PRNG and erf_inv, reproduced). New fields NodeField.alpha, sensoryPrecision, nTotal, nActiveCluster, and VectorField.n, expectedMeans, expectedSigmas, activated. Checked against pyhgf JAX on 6 new fixtures (VM, dart2js, dart2wasm, -O4). Unlike pyhgf, missing observations are skipped, the node may follow a continuous one, and a cluster count that doesn't match batchSize is reported at build(). About 1.3 ms per trial on AOT (pyhgf JAX: 3.8 ms). BatchNetwork and sample don't take them yet.

  • Update order: an ef-state node without parents takes its step on the first pass even when it has children, as in pyhgf (only dp-state clusters are affected).

  • Categorical state nodes (NodeKind.categoricalState, Network.addCategoricalState): one-hot observations over n categories, one binary HGF per category with a shared volatility parent (pyhgf's 2n + 2 nodes), and the implied Dirichlet distribution (VectorField.alpha), its KL divergence (NodeField.klDivergence) and surprise (NodeField.surprise). Checked against pyhgf JAX on 7 new fixtures (VM, dart2js, dart2wasm, -O4). Unlike pyhgf, several categorical nodes can share a network, a categorical node can follow a continuous one (pyhgf crashes), and the implied nodes take parameters. BatchNetwork and sample don't take them yet.

  • logGamma, gammaSign, digamma and dirichletKullbackLeibler (in log space: finite where pyhgf's overflows to NaN).

  • Trajectories: asking for a field that wasn't recorded now names it.

  • Exponential-family state nodes (NodeKind.efState, Network.addEfState): univariate or multivariate normal sufficient statistics, with a fixed learning rate (nus) or HGF learning (EfLearning.hgf1/2/3, which adds pyhgf's implied continuous nodes). Checked against pyhgf JAX on 11 new fixtures (VM, dart2js, dart2wasm, -O4).

  • Vector-valued attributes: VectorField (mean, xis, observation_ss), Network.getVector / setVector / getInitialVector / setInitialVector / vectorLength, recorded in Trajectories (vectorFields, vectorSeries, vectorAt, and in toJson). NodeField.nus.

  • Inputs may span several columns: Network.nInputColumns. Breaking for networks with multivariate inputs only: observed is one flag per input node (nTime × nInputs), as in pyhgf; unchanged otherwise.

  • UpdateStep.pyhgfName: the JAX function name of each step. The parity tests now also check the update order against pyhgf's JAX schedule.

  • BatchNetwork: B copies of a Network run in lock step, with per-element initial values (setInitial, setInitialAt) and coupling strengths (setValueCoupling, setVolatilityCoupling), shared or per-element observations, inputData / surprise (per-element totals and per-trial) / step. Each element matches Network bit for bit (checked on every fixture on the VM, dart2js and dart2wasm, including -O4). The update steps run stage by stage over blocks of elements, so the CPU overlaps the elements' exps and divisions. Per element-trial that is 1.4–1.9× faster than looping a Network on AOT, and 1.2–1.5× on Wasm. No trajectory recording yet.

  • ResponseFunction.batchSurprise (implemented by every built-in model) and ResponseFunction.fn(..., batch:).

  • Network.setValueCoupling / setVolatilityCoupling, to change a coupling strength (e.g. a fitted κ) after building.

  • Surprise and response functions: gaussianSurprise, binarySurprise, binarySurpriseFinitePrecision, gaussianDensity, sigmoidInverseTemperature; the ResponseFunction interface with ports of pyhgf.response and a GaussianResponse model; Network.surprise (no recording, optional per-trial output); inputData(response:); Trajectories.nodeSurprise / totalSurprise / responseSurprise. Checked against pyhgf on every fixture (VM, dart2js, dart2wasm).

  • NodeKind.constantState (pyhgf's bias node).

  • Custom value-coupling functions: the Coupling interface (implemented by CouplingFn) and CustomCoupling with user g, g', g'' and a finite-difference check(); NetworkSpec.build(couplings: ...) resolves them by name. No cost on the named functions.

  • Generative mode: Network.sample (pyhgf's sample), and saveState/restoreState (NetworkState).

  • Network.inputIdxs no longer allocates on each call.

  • Network.ehgfMgfCorrection (spec key ehgf_mgf_correction), opt-in and diverging from pyhgf 0.3.2: adds the relaxed prediction's Σ κ²/(2π̂) terms to the eHGF volatility re-prediction. Without them, relaxed eHGF diverges on 3-level continuous HGFs. Checked against pyhgf JAX patched with the same change; see the README and example/ehgf_mgf_correction.dart.

  • inputData(into: traj) re-records into an existing Trajectories of the same shape. Recording is staged in blocks: on AOT about 2× cheaper, and 6× with into:.

  • Faster on Wasm: the unbounded update does fewer exp/log calls, dart2wasm builds use a table-driven exp, and hot-path columns are no longer boxed. On the 3-level 10k series, AOT went 13.8 → 9.2 ms and Wasm 24.2 → 13.6 ms.

0.1.0-dev.1 #

  • Initial feasibility spike: nodalised continuous and binary HGF engine (standard, eHGF and unbounded volatility updates; relaxed and mean-field value coupling; non-linear coupling functions; missing observations; irregular time steps), checked against pyhgf to 1e-9 on the VM, dart2js and dart2wasm.
  • Network.inputData / step / predict / reset / setInitial, Trajectories (CSV/JSON export), NetworkSpec (JSON networks).
0
likes
160
points
114
downloads

Documentation

API reference

Publisher

unverified uploader

Weekly Downloads

Hierarchical Gaussian Filter, generalised predictive-coding. Dart pyhgf port.

Homepage
Repository (GitHub)
View/report issues

Topics

#neuroscience #bayesian #predictive-coding #computational-psychiatry #filtering

License

MIT (license)

More

Packages that depend on hgf