hgf 0.1.1
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,BatchNetworkand its tangents. Newshared_child_*fixtures. - #486's default (
coupling_moments="taylor") matches up to rounding. The opt-in"exact"moments are not ported yet.
- #484: volatility parents enter the predicted volatility at their
predicted means under the relaxed updates too. The MGF terms
0.1.0 #
-
DpProposals(withdpProposalCount,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, whichCategoricalSurprisefits counted.Network,BatchNetwork,CategoricalSurprise's gradients; inNetworkFixes.toJsonascategorical_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), soNetwork.ehgfMgfCorrection, its spec and JSON keys andexample/ehgf_mgf_correction.dartare removed (an old"ehgf_mgf_correction"key is ignored on read). Fixtures regenerated at pyhgf4db3b093. -
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,BatchNetworkand its tangents. OnlytimeSteps≠ 1 changes results. Fixtures regenerated at pyhgfd9958ece. 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 newUpdateStep.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.NetworkandBatchNetwork(bit for bit, tangents included). Fixtures regenerated at pyhgf1e6e98d7, with 21noise_parent_*scenarios. -
NetworkFixes(Network(fixes:),Network.defaultFixes,-DHGF_UPSTREAM=true): corrections of pyhgf bugs, on by default (recommended), off for parity (none). The first isconstantNoiseVariance(P21: pyhgf adds a bias parent's placeholder precision to the noise prediction error). IntoJson/fromJsonandNetworkSpec("fixes"). -
gaussianDensityis normalised for every precision (pyhgf #475): the leading factor is√π / √(2π), notπ / √(2π). This shiftsbinarySurpriseFinitePrecisionby−½ log π. -
lambertW0divides 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 nextstep, asNetwork.predictis; 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.surpriseholds the observation's surprise under the node's Chinese-restaurant-process predictive,−log(Σᵢ nᵢ/(α+N) N(x; μᵢ, σᵢ) + α/(α+N) p₀(x)), withp₀the base measure's predictive (the mean density of the 20 000 proposals; not the candidate cluster, which is fitted toxand would reward one cluster per observation). Log-space, 0 on a missing observation, inNetworkandBatchNetwork(bit-identical).DpSurprisesums it over dp inputs; no gradients (the likelihood jumps where an assignment flips).Trajectories.nodeSurprisestays NaN for dp nodes, as in pyhgf. -
benchmark/bin/dp_cost.dart: ~1 ms per dp element-trial (AOT and JIT). -
BatchNetworkruns dp-state nodes too (batch/batch_vectors.dart), so it now takes every node kind. Each element has its own α, sensory precision and clusters (getVectorreadsn,expectedMeans,expectedSigmas,activated), and matchesNetworkbit for bit on the 6 dp fixtures (VM, dart2js, dart2wasm,-O4).DpScratchhas per-slot proposal row caches (slots:,dpCandidate(slot:)), one per element of a block. dp networks capblockSizeat the slots that fit in 64 MB (52 with 4 clusters). AOT: 1.18 ms per element-trial vsNetwork's 1.25–1.29 ms (4 clusters, 32 elements). -
BatchNetworkruns ef-state and categorical-state nodes (batched kernels inbatch/batch_vectors.dart, a per-element vector side store[offset][element], multi-column inputs;getVector). Each element matchesNetworkbit 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'ssurprise,Σ binarySurprise(xₖ, μ̂ₖ)over its categories), batched and differentiable. -
BatchNetwork.valueParentCount/valueParent: a node's value parents without allocating (for response functions). -
BatchNetworkdata rows arenInputColumnswide (the observed flags stay one per input node), as forNetwork. -
CouplingFn.tanhuses 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 withsetInitial/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)carrieskforward-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 withsetInitialTangent,setValueCouplingTangentandsetVolatilityCouplingTangent, read withgetTangent/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/supportsGradientsandSurprisePartials: a response function reports∂surprise/∂belieffor 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 ofd2gotherwise). -
sigmoidInverseTemperaturecomputesσ(β · logit x)instead ofx^β / (x^β + (1 − x)^β): the same function (agrees to 1e-13 relative, same values at 0 and 1), about 3x faster, which makesBinarySoftmaxInverseTemperature~25% cheaper per trial in a batch. -
Read-only graph accessors:
Network.valueParentsOf,valueChildrenOf,volatilityParentsOf,volatilityChildrenOf, their coupling strengths (valueParentStrengthsOf,volatilityParentStrengthsOf) andcouplingOf, for drawing and inspecting a network. -
Dirichlet process nodes (
NodeKind.dpState,Network.addDpState, andNetwork.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 anderf_inv, reproduced). New fieldsNodeField.alpha,sensoryPrecision,nTotal,nActiveCluster, andVectorField.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 matchbatchSizeis reported atbuild(). About 1.3 ms per trial on AOT (pyhgf JAX: 3.8 ms).BatchNetworkandsampledon'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 overncategories, one binary HGF per category with a shared volatility parent (pyhgf's2n + 2nodes), 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.BatchNetworkandsampledon't take them yet. -
logGamma,gammaSign,digammaanddirichletKullbackLeibler(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 inTrajectories(vectorFields,vectorSeries,vectorAt, and intoJson).NodeField.nus. -
Inputs may span several columns:
Network.nInputColumns. Breaking for networks with multivariate inputs only:observedis 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 aNetworkrun 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 matchesNetworkbit 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 aNetworkon AOT, and 1.2–1.5× on Wasm. No trajectory recording yet. -
ResponseFunction.batchSurprise(implemented by every built-in model) andResponseFunction.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; theResponseFunctioninterface with ports ofpyhgf.responseand aGaussianResponsemodel;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
Couplinginterface (implemented byCouplingFn) andCustomCouplingwith user g, g', g'' and a finite-differencecheck();NetworkSpec.build(couplings: ...)resolves them by name. No cost on the named functions. -
Generative mode:
Network.sample(pyhgf'ssample), andsaveState/restoreState(NetworkState). -
Network.inputIdxsno longer allocates on each call. -
Network.ehgfMgfCorrection(spec keyehgf_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 andexample/ehgf_mgf_correction.dart. -
inputData(into: traj)re-records into an existingTrajectoriesof the same shape. Recording is staged in blocks: on AOT about 2× cheaper, and 6× withinto:. -
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).