Belief Propagation API
Status: Generated from current Python docstrings and type hints.
Inference backend surface for factor graphs, lowering, exact inference, junction tree inference, TRW-BP, Mean Field VI, and engine results.
gaia.engine.bp
BP v2 — belief propagation aligned with theory and Gaia IR.
Theory: docs/foundations/theory/06-factor-graphs.md, 07-belief-propagation.md IR lowering: docs/foundations/gaia-ir/07-lowering.md
CLI 主路径使用 InferenceEngine.run() 自动 dispatch:
junction_tree → treewidth ≤ 20,精确
trw_bp → n ≤ 2000 且 treewidth > 20,有界近似
mean_field → n > 2000,大图快速近似
本模块下方的 infer() 是旧的便利函数,仍保留 loopy_bp 强制模式和
大图 loopy-BP fallback 以兼容旧调用;新代码需要和 gaia run infer 一致时,
应直接使用 InferenceEngine。
BeliefPropagation
BeliefPropagation(damping: float = 0.5, max_iterations: int = 100, convergence_threshold: float = 1e-06)
Sum-product loopy Belief Propagation on a FactorGraph (v2).
Implements bp.md §3 exactly, with the following design principles: - All messages are 2-vectors [P(x=0), P(x=1)], always normalized. - Synchronous schedule: all new messages computed from old, then swapped. - Damping per bp.md §4 prevents oscillation in loopy graphs. - Relation variables (CONTRADICTION/EQUIVALENCE) participate fully. - BPDiagnostics always collected (full belief history).
damping: α in bp.md §4. Default 0.5. Range (0, 1]. 1.0 = fully replace old message (fast, may oscillate). 0.5 = half-step (default, balanced stability). Lower values increase stability but slow convergence. max_iterations: Upper bound on sweep iterations. convergence_threshold: Stop early when max|Δbelief| < threshold across all variables.
Initialize loopy BP with damping and convergence controls.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
damping
|
float
|
Message damping factor in |
0.5
|
max_iterations
|
int
|
Maximum number of synchronous BP sweeps. |
100
|
convergence_threshold
|
float
|
Stop when the maximum belief change falls below this value. |
1e-06
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in gaia/engine/bp/bp.py
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 | |
run
run(graph: FactorGraph) -> BPResult
Run loopy BP on graph and return beliefs + diagnostics.
Always returns a BPResult with full diagnostics (never None).
graph: A validated FactorGraph. Variables referenced by factors must be registered. Cromwell clamping is enforced at graph construction.
Returns:
| Type | Description |
|---|---|
BPResult
|
A BPResult containing posterior |
Source code in gaia/engine/bp/bp.py
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 | |
EngineConfig
dataclass
EngineConfig(jt_max_treewidth: int = JT_MAX_TREEWIDTH, mf_node_limit: int = MF_NODE_LIMIT, trw_damping: float = 0.5, trw_max_iter: int = 200, trw_threshold: float = 1e-08, mf_max_iter: int = 500, exact_max_vars: int = EXACT_MAX_VARS)
InferenceEngine 的配置参数。.
jt_max_treewidth: treewidth ≤ 此值时使用 JT(精确)。 mf_node_limit: 节点数 > 此值时使用 Mean Field VI。 trw_damping: TRW-BP 阻尼系数。 trw_max_iter: TRW-BP 最大迭代次数。 trw_threshold: TRW-BP 收敛阈值。 mf_max_iter: Mean Field 最大迭代次数。 exact_max_vars: 暴力枚举最大变量数。
InferenceEngine
InferenceEngine(config: EngineConfig | None = None)
统一推断引擎,自动选择最优算法。.
自动路由策略(method='auto'): 1. n > mf_node_limit → Mean Field VI(大图快速近似) 2. treewidth ≤ jt_max_treewidth → JT(精确) 3. 其他 → TRW-BP(有界近似)
config: EngineConfig,控制路由阈值和算法参数。
Initialize the inference engine with optional configuration.
Source code in gaia/engine/bp/engine.py
127 128 129 130 131 132 133 134 135 136 137 | |
run
run(graph: FactorGraph, method: MethodChoice = 'auto') -> InferenceResult
在 graph 上运行推断。.
graph: 已 lower 好的 FactorGraph。 method: 'auto'(默认):按 n 和 treewidth 自动选择。 'jt':强制 JT(精确,treewidth ≤ 20)。 'trw_bp':强制 TRW-BP。 'mean_field':强制 Mean Field VI。 'exact':强制暴力枚举(仅适用于小图)。
Returns:
| Type | Description |
|---|---|
InferenceResult
|
InferenceResult,包含边缘概率、算法元数据和耗时。 |
Source code in gaia/engine/bp/engine.py
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 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 | |
benchmark
benchmark(graph: FactorGraph) -> dict[str, dict[str, object]]
运行所有可行算法并返回对比结果。.
Source code in gaia/engine/bp/engine.py
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 | |
InferenceResult
dataclass
InferenceResult(result: TRWResult | MFResult, method_used: str = 'unknown', treewidth: int = -1, elapsed_ms: float = 0.0, is_exact: bool = False)
InferenceEngine 的返回值,包含推断结果和算法元数据。.
result: 底层算法的结果(TRWResult 或 MFResult)。 method_used: 实际使用的算法:'jt', 'trw_bp', 'mean_field', 或 'exact'。 treewidth: 因子图的估计树宽(未计算时为 -1)。 elapsed_ms: 推断耗时(毫秒)。 is_exact: True 表示算法保证返回精确边缘概率。
beliefs
property
beliefs: dict[str, float]
快捷访问 beliefs 字典。.
diagnostics
property
diagnostics: TRWDiagnostics | MFDiagnostics
快捷访问 diagnostics。.
Factor
dataclass
Factor(factor_id: str, factor_type: FactorType, variables: list[str], conclusion: str, p1: float | None = None, p2: float | None = None, cpt: tuple[float, ...] | None = None)
Factor in a factor graph with variables and potential function.
all_vars
property
all_vars: list[str]
Return all variables involved in this factor.
FactorGraph
FactorGraph()
Factor graph for probabilistic inference.
Initialize an empty factor graph.
Source code in gaia/engine/bp/factor_graph.py
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | |
add_variable
add_variable(var_id: str, prior: float | None = None) -> None
Register a binary variable, optionally with an explicit unary factor.
variables records the neutral display/initial measure for every
variable. Only unary_factors is a Jaynes-style class IV soft prior
(Cromwell ε permitted). Class I logical assertions belong in
hard_evidence via :meth:add_evidence — those install a Cromwell-
clamped {ε, 1-ε} strong prior (Gaia\'s adjusted Jaynes semantics), not
a strict δ; downstream BP treats hard-evidence variables as pinned but
still Bayes-updatable.
Source code in gaia/engine/bp/factor_graph.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 114 115 116 | |
add_evidence
add_evidence(var_id: str, value: int) -> None
Class I hard observation with Cromwell clamp.
Gaia adjusts Jaynes: hard evidence is stored as a very strong soft prior {ε, 1-ε} (ε = CROMWELL_EPS = 1e-3), not as strict δ {0, 1}. This preserves Bayesian updatability (Cromwell's rule) and prevents log(0) pathologies in BP message passing, at the cost of a small O(ε) systematic bias vs. strict Jaynes Class I semantics.
Source code in gaia/engine/bp/factor_graph.py
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 | |
observe
observe(var_id: str, value: int) -> None
Hard evidence alias — delegates to :meth:add_evidence.
Source code in gaia/engine/bp/factor_graph.py
147 148 149 | |
add_likelihood
add_likelihood(var_id: str, likelihood_ratio: float) -> None
Soft evidence (class II): fold likelihood ratio into the class-IV unary.
P_new(x=1) = normalize(π · lr, (1−π) · 1) where lr = P(E|x=1)/P(E|x=0). Records the update in posterior_evidence[var_id] for audit.
Source code in gaia/engine/bp/factor_graph.py
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 | |
add_factor
add_factor(factor_id: str, factor_type: FactorType, variables: Sequence[str], conclusion: str, *, p1: float | None = None, p2: float | None = None, cpt: Sequence[float] | None = None) -> None
Add a factor to the graph with specified type and variables.
Source code in gaia/engine/bp/factor_graph.py
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 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 | |
get_var_to_factors
get_var_to_factors() -> dict[str, list[int]]
Return mapping from variable names to factor indices.
Source code in gaia/engine/bp/factor_graph.py
320 321 322 323 324 325 326 327 328 329 330 331 332 333 | |
validate
validate() -> list[str]
Validate the factor graph and return list of errors.
Source code in gaia/engine/bp/factor_graph.py
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 | |
summary
summary() -> str
Generate summary string of the factor graph.
Source code in gaia/engine/bp/factor_graph.py
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 | |
FactorType
Bases: Enum
Enumeration of factor types in the factor graph.
JointDistribution
Bases: BaseModel
A normalized joint table over a binary variable set.
JointQueryUnavailable
Bases: BaseModel
A method-specific joint query miss.
JointQueryUnavailableError
JointQueryUnavailableError(method: JointQueryMethod, variables: Sequence[str], reason: str, diagnostics: dict[str, Any] | None = None)
Bases: RuntimeError
Raised when a method cannot provide a requested joint distribution.
Initialize an unavailable joint-query error.
Source code in gaia/engine/bp/joint_query.py
32 33 34 35 36 37 38 39 40 41 42 43 44 | |
JunctionTreeInference
Exact inference via the Junction Tree Algorithm.
Converts the FactorGraph to a Junction Tree (chordal graph with clique potentials), then runs exact two-pass message passing (Shafer-Shenoy collect + distribute). The result is mathematically identical to brute-force enumeration but runs in O(n * 2^w) time.
This fixes loopy BP's double-counting error on graphs with short cycles. For Gaia's factor graphs (treewidth ≤ ~15), this is the preferred engine.
Returns the same TRWResult interface as BeliefPropagation for drop-in use.
run
run(graph: FactorGraph) -> TRWResult
Run exact Junction Tree inference on graph.
Parameters
graph: A validated FactorGraph. All variables referenced by factors must be registered.
Returns:
| Type | Description |
|---|---|
TRWResult
|
TRWResult containing exact marginal |
TRWResult
|
diagnostics recording treewidth and clique count. |
Source code in gaia/engine/bp/junction_tree.py
760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 | |
MeanFieldVI
MeanFieldVI(max_iterations: int = 500, convergence_threshold: float = 1e-06, track_elbo: bool = False)
Coordinate Ascent Variational Inference (CAVI) for binary factor graphs.
Scales to large graphs (n > 2000) where Junction Tree and TRW-BP are too expensive. Complexity O(n * F * 2^k) per sweep.
Parameters
max_iterations: Maximum number of full CAVI sweeps. convergence_threshold: Stop when max|delta_mu| < threshold. track_elbo: If True, compute and record ELBO after each sweep (adds O(F*2^k) cost).
Initialize mean field inference state.
Source code in gaia/engine/bp/mean_field.py
216 217 218 219 220 221 222 223 224 225 | |
run
run(graph: FactorGraph) -> MFResult
Run CAVI on graph and return beliefs + diagnostics.
Source code in gaia/engine/bp/mean_field.py
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 | |
TRWBeliefPropagation
TRWBeliefPropagation(damping: float = 0.5, max_iterations: int = 200, convergence_threshold: float = 1e-06, schedule: str = 'synchronous')
Tree-Reweighted Belief Propagation (Wainwright et al. 2003/2005).
Replaces loopy BP as the default approximate inference algorithm. Uses factor-level reweighting for higher-order factor graphs.
Parameters
damping: Message mixing coefficient alpha in (0, 1]. Default 0.5. max_iterations: Maximum number of full sweeps. convergence_threshold: Stop when max|delta_belief| < threshold. schedule: "synchronous" -- standard parallel sweep (default). "residual" -- currently rejected; residual TRW-BP is not yet stable.
Initialize TRW-BP oscillation diagnostic state.
Source code in gaia/engine/bp/trw_bp.py
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 | |
run
run(graph: FactorGraph) -> TRWResult
Run TRW-BP on graph and return beliefs + diagnostics.
Source code in gaia/engine/bp/trw_bp.py
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 | |
exact_inference
exact_inference(graph: FactorGraph) -> tuple[dict[str, float], float]
Compute exact marginal beliefs via enumeration over joint distribution.
Source code in gaia/engine/bp/exact.py
199 200 201 202 203 204 205 206 207 208 209 210 211 212 | |
exact_joint_over
exact_joint_over(graph: FactorGraph, free_vars: list[str]) -> np.ndarray
Return the normalized joint over free_vars by exact enumeration.
The result is indexed by the bit pattern over free_vars in order:
index sum(v_i << i for i, v_i in enumerate(free_vars)).
Source code in gaia/engine/bp/exact.py
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 | |
compare_joint_over
compare_joint_over(graph: FactorGraph, variables: Sequence[str], *, methods: Sequence[JointQueryMethod] = ('exact', 'junction_tree', 'trw_bp', 'mean_field')) -> list[JointDistribution | JointQueryUnavailable]
Run several joint providers and collect unavailable methods explicitly.
Source code in gaia/engine/bp/joint_query.py
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 | |
joint_over
joint_over(graph: FactorGraph, variables: Sequence[str], *, method: JointQueryMethod) -> JointDistribution
Return a joint table over variables using one inference method.
Source code in gaia/engine/bp/joint_query.py
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 | |
jt_treewidth
jt_treewidth(graph: FactorGraph) -> int
Estimate the treewidth of the factor graph via min-fill triangulation.
Returns the size of the largest maximal clique minus 1.
Source code in gaia/engine/bp/junction_tree.py
655 656 657 658 659 660 661 662 663 664 665 | |
lower_local_graph
lower_local_graph(canonical: LocalCanonicalGraph, *, node_priors: dict[str, float] | None = None, strategy_conditional_params: dict[str, list[float]] | None = None, expand_formal: bool = True, infer_use_degraded_noisy_and: bool = False, review_manifest: ReviewManifest | None = None) -> FactorGraph
Build a FactorGraph from a local canonical Gaia IR graph.
Parameters
canonical:
Local graph with knowledges, operators, strategies.
node_priors:
Optional prior P(claim=1) per Knowledge id (claim nodes only).
strategy_conditional_params:
Maps strategy_id -> conditional_probabilities list (infer: 2^k entries,
noisy_and: 1 entry).
expand_formal:
If True, expand FormalStrategy to deterministic factors. If False,
raises NotImplementedError; folded FormalStrategy lowering is a
future backend path.
infer_use_degraded_noisy_and:
If True, lower infer with CONJUNCTION+SOFT_ENTAILMENT using only
all-true / all-false CPT entries (information loss for general CPT).
review_manifest:
Optional qualitative ReviewManifest. When present, v6 action-backed
strategies/operators are lowered only after their latest review is
accepted. Legacy IR targets without metadata.action_label are not
gated.
Source code in gaia/engine/bp/lowering.py
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 | |
merge_factor_graphs
merge_factor_graphs(local_fg: FactorGraph, dep_graphs: list[tuple[str, FactorGraph, str]], *, local_prefix: str) -> FactorGraph
Merge local and dependency factor graphs for joint inference.
Parameters
local_fg:
The local package's factor graph.
dep_graphs:
List of (dep_import_name, dep_factor_graph, dep_qid_prefix)
triples. dep_qid_prefix identifies variables owned by that
dependency, e.g. "github:dep_pkg::".
local_prefix:
QID prefix for the local package, e.g. "github:my_pkg::".
Variables starting with this prefix are owned by the local package.
Returns:
| Type | Description |
|---|---|
FactorGraph
|
A merged :class: |
FactorGraph
|
variable (dep-owned prior takes precedence for dep nodes) and all |
FactorGraph
|
factors coexist with prefixed IDs to avoid collision. |
Source code in gaia/engine/bp/lowering.py
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 | |
infer
infer(graph: FactorGraph, method: str = 'auto') -> dict[str, float]
Legacy convenience wrapper: infer FactorGraph marginals.
Prefer :class:InferenceEngine for new code and CLI-parity behavior.
Parameters
graph: 已 lower 好的 FactorGraph。 method: "auto" — 按 treewidth / n 自动选择算法 "junction_tree" — 强制 JT(精确,treewidth ≤ 20) "trw_bp" — 强制 TRW-BP "loopy_bp" — legacy force Loopy BP "mean_field" — force Mean Field VI
Returns:
dict[str, float] 变量 ID → P(x=1) 的边缘概率。
Source code in gaia/engine/bp/__init__.py
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 | |