mbi 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
mbi-1.0.0/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
mbi-1.0.0/PKG-INFO ADDED
@@ -0,0 +1,50 @@
1
+ Metadata-Version: 2.4
2
+ Name: mbi
3
+ Version: 1.0.0
4
+ Summary: Marginal-based estimation and inference (with applications to differential privacy)
5
+ Author-email: Ryan McKenna <rmckenna21@gmail.com>
6
+ License: Apache License 2.0
7
+ Project-URL: Homepage, https://github.com/ryan112358/mbi
8
+ Project-URL: Repository, https://github.com/ryan112358/mbi
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: License :: OSI Approved :: Apache Software License
11
+ Classifier: Operating System :: OS Independent
12
+ Requires-Python: >=3.9
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: attrs
16
+ Requires-Dist: numpy
17
+ Requires-Dist: scipy
18
+ Requires-Dist: pandas
19
+ Requires-Dist: networkx
20
+ Requires-Dist: jax
21
+ Requires-Dist: jaxlib
22
+ Requires-Dist: chex
23
+ Requires-Dist: optax
24
+ Provides-Extra: dev
25
+ Requires-Dist: pytest; extra == "dev"
26
+ Requires-Dist: pytype; extra == "dev"
27
+ Requires-Dist: parameterized; extra == "dev"
28
+ Requires-Dist: yapf; extra == "dev"
29
+ Requires-Dist: pylint; extra == "dev"
30
+ Requires-Dist: pydocstyle; extra == "dev"
31
+ Provides-Extra: docs
32
+ Requires-Dist: sphinx; extra == "docs"
33
+ Requires-Dist: sphinx-rtd-theme; extra == "docs"
34
+ Requires-Dist: myst-parser; extra == "docs"
35
+ Dynamic: license-file
36
+
37
+ ## MBI: Marginal-Based Estimation and Inference
38
+ **(with applications to differential privacy)**
39
+
40
+ <img src="pgm-logo.png" alt="drawing" width="123"/>
41
+
42
+ [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.5548533.svg)](https://doi.org/10.5281/zenodo.5548533)
43
+ [![Continuous integration](https://github.com/ryan112358/private-pgm/actions/workflows/main.yml/badge.svg)](https://github.com/ryan112358/private-pgm/actions/workflows/main.yml)
44
+ [![Documentation Status](https://app.readthedocs.org/projects/private-pgm/badge/?version=latest)](https://private-pgm.readthedocs.io/en/latest/)
45
+
46
+ ![Metrics for ryan112358/private-pgm repository](https://raw.githubusercontent.com/ryan112358/ryan112358/main/metrics.private-pgm.svg)
47
+
48
+
49
+ Documentation has been moved to
50
+ [https://private-pgm.readthedocs.io/en/latest/](https://private-pgm.readthedocs.io/en/latest/)!
mbi-1.0.0/README.md ADDED
@@ -0,0 +1,14 @@
1
+ ## MBI: Marginal-Based Estimation and Inference
2
+ **(with applications to differential privacy)**
3
+
4
+ <img src="pgm-logo.png" alt="drawing" width="123"/>
5
+
6
+ [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.5548533.svg)](https://doi.org/10.5281/zenodo.5548533)
7
+ [![Continuous integration](https://github.com/ryan112358/private-pgm/actions/workflows/main.yml/badge.svg)](https://github.com/ryan112358/private-pgm/actions/workflows/main.yml)
8
+ [![Documentation Status](https://app.readthedocs.org/projects/private-pgm/badge/?version=latest)](https://private-pgm.readthedocs.io/en/latest/)
9
+
10
+ ![Metrics for ryan112358/private-pgm repository](https://raw.githubusercontent.com/ryan112358/ryan112358/main/metrics.private-pgm.svg)
11
+
12
+
13
+ Documentation has been moved to
14
+ [https://private-pgm.readthedocs.io/en/latest/](https://private-pgm.readthedocs.io/en/latest/)!
@@ -0,0 +1,52 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "mbi"
7
+ version = "1.0.0"
8
+ description = "Marginal-based estimation and inference (with applications to differential privacy)"
9
+ authors = [
10
+ {name = "Ryan McKenna", email = "rmckenna21@gmail.com"},
11
+ ]
12
+ license = {text = "Apache License 2.0"}
13
+ readme = "README.md"
14
+ requires-python = ">=3.9"
15
+ classifiers = [
16
+ "Programming Language :: Python :: 3",
17
+ "License :: OSI Approved :: Apache Software License",
18
+ "Operating System :: OS Independent",
19
+ ]
20
+ dependencies = [
21
+ "attrs",
22
+ "numpy",
23
+ "scipy",
24
+ "pandas",
25
+ "networkx",
26
+ "jax",
27
+ "jaxlib",
28
+ "chex",
29
+ "optax",
30
+ ]
31
+
32
+ [project.urls]
33
+ Homepage = "https://github.com/ryan112358/mbi"
34
+ Repository = "https://github.com/ryan112358/mbi"
35
+
36
+ [project.optional-dependencies]
37
+ dev = [
38
+ "pytest",
39
+ "pytype",
40
+ "parameterized",
41
+ "yapf",
42
+ "pylint",
43
+ "pydocstyle",
44
+ ]
45
+ docs = [
46
+ "sphinx",
47
+ "sphinx-rtd-theme",
48
+ "myst-parser",
49
+ ]
50
+
51
+ [tool.setuptools.packages.find]
52
+ where = ["src"]
mbi-1.0.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,36 @@
1
+ """Main entry point for the mbi package.
2
+
3
+ This module exposes the core classes and submodules of the mbi library,
4
+ making them available for direct import. It simplifies access to functionalities
5
+ like data representation (Domain, Dataset), factor manipulation (Factor),
6
+ and various estimation and oracle modules.
7
+ """
8
+ from . import callbacks, estimation, junction_tree, marginal_oracles
9
+ from .clique_vector import CliqueVector
10
+ from .dataset import Dataset
11
+ from .domain import Domain
12
+ from .estimation import Estimator
13
+ from .factor import Factor, Projectable
14
+ from .marginal_loss import LinearMeasurement, MarginalLossFn
15
+ from .marginal_oracles import MarginalOracle
16
+ from .markov_random_field import MarkovRandomField
17
+
18
+ Clique = tuple[str, ...]
19
+
20
+ __all__ = [
21
+ 'Domain',
22
+ 'Dataset',
23
+ 'Factor',
24
+ 'Clique',
25
+ 'CliqueVector',
26
+ 'LinearMeasurement',
27
+ 'MarginalLossFn',
28
+ 'MarkovRandomField',
29
+ 'Projectable',
30
+ 'MarginalOracle',
31
+ 'Estimator',
32
+ 'estimation',
33
+ 'callbacks',
34
+ 'junction_tree',
35
+ 'marginal_oracles',
36
+ ]
@@ -0,0 +1,228 @@
1
+ """Approximate marginal oracles with convex counting numbers.
2
+
3
+ See the paper ["Relaxed Marginal Consistency for Differentially Private Query Answering"](https://arxiv.org/pdf/2109.06153) for more details.
4
+
5
+ This file implements one approximate marginal inference oracle: Convex-GBP
6
+ with fixed counting numbers of 1.0 for all regions. We experimented with
7
+ others, but do not officially support them in this library. If interested,
8
+ please see the following snapshot of this repository:
9
+
10
+ https://github.com/ryan112358/private-pgm/tree/approx-experiments-snapshot
11
+
12
+ Pull requests are welcome to add support for other approximate oracles.
13
+ """
14
+
15
+ import functools
16
+ import itertools
17
+ from typing import Any, Protocol, TypeAlias
18
+
19
+ import jax
20
+ import networkx as nx
21
+ from scipy.cluster.hierarchy import DisjointSet
22
+
23
+ from .clique_vector import CliqueVector
24
+ from .domain import Domain
25
+ from .factor import Factor
26
+
27
+ Clique: TypeAlias = tuple[str, ...]
28
+
29
+ # pylint: disable
30
+
31
+
32
+ class StatefulMarginalOracle(Protocol):
33
+ """
34
+ Defines the callable signature for stateful marginal oracle functions.
35
+
36
+ A stateful marginal oracle computes (approximate) marginals from
37
+ log-space potentials while also managing an internal state, often
38
+ for optimization in iterative algorithms (e.g., preserving messages
39
+ in message passing).
40
+ """
41
+ def __call__(
42
+ self,
43
+ potentials: CliqueVector,
44
+ total: float = 1.0,
45
+ state: Any = None,
46
+ mesh: jax.sharding.Mesh | None = None
47
+ ) -> tuple[CliqueVector, Any]:
48
+ """
49
+ Computes marginals from log-space potentials and manages state.
50
+
51
+ Args:
52
+ potentials: A CliqueVector representing the log-space potentials
53
+ of a graphical model.
54
+ total: The normalization factor, typically the total number of
55
+ records or a probability sum. Defaults to 1.0.
56
+ state: An optional argument to pass state between calls.
57
+ The oracle may use this state and return an updated version.
58
+ mesh: Specifies how the computation will be sharded across devices.
59
+
60
+ Returns:
61
+ A tuple containing:
62
+ - CliqueVector: The computed marginals.
63
+ - Any: The updated state.
64
+ """
65
+ ...
66
+
67
+
68
+ def build_graph(domain: Domain, cliques: list[tuple[str, ...]]) -> ...:
69
+ """Builds the region graph for convex generalized belief propagation."""
70
+ # Hard-code minimal=True, convex=True
71
+ # Counting numbers = 1 for all regions
72
+ # Alg 11.3 of Koller & Friedman
73
+ regions = set(cliques)
74
+ size = 0
75
+ while len(regions) > size:
76
+ size = len(regions)
77
+ for r1, r2 in itertools.combinations(regions, 2):
78
+ z = tuple(sorted(set(r1) & set(r2)))
79
+ if len(z) > 0 and not z in regions:
80
+ regions.update({z})
81
+
82
+ G = nx.DiGraph()
83
+ G.add_nodes_from(regions)
84
+ for r1 in regions:
85
+ for r2 in regions:
86
+ if set(r2) < set(r1) and not any(
87
+ set(r2) < set(r3) and set(r3) < set(r1) for r3 in regions
88
+ ):
89
+ G.add_edge(r1, r2)
90
+
91
+ H = G.reverse()
92
+ G1, H1 = nx.transitive_closure(G), nx.transitive_closure(H)
93
+
94
+ children = {r: list(G.neighbors(r)) for r in regions}
95
+ parents = {r: list(H.neighbors(r)) for r in regions}
96
+ descendants = {r: list(G1.neighbors(r)) for r in regions}
97
+ ancestors = {r: list(H1.neighbors(r)) for r in regions}
98
+ forebears = {r: set([r] + ancestors[r]) for r in regions}
99
+ downp = {r: set([r] + descendants[r]) for r in regions}
100
+
101
+ min_edges = []
102
+ for r in regions:
103
+ ds = DisjointSet()
104
+ for u in parents[r]:
105
+ ds.add(u)
106
+ for u, v in itertools.combinations(parents[r], 2):
107
+ uv = set(ancestors[u]) & set(ancestors[v])
108
+ if len(uv) > 0:
109
+ ds.merge(u, v)
110
+ canonical = set()
111
+ for u in parents[r]:
112
+ canonical.update({ds[u]})
113
+ min_edges.extend([(u, r) for u in canonical])
114
+
115
+ G = nx.DiGraph()
116
+ G.add_nodes_from(regions)
117
+ G.add_edges_from(min_edges)
118
+
119
+ H = G.reverse()
120
+ G1, H1 = nx.transitive_closure(G), nx.transitive_closure(H)
121
+
122
+ children = {r: list(G.neighbors(r)) for r in regions}
123
+ parents = {r: list(H.neighbors(r)) for r in regions}
124
+
125
+ messages = {}
126
+ message_order = []
127
+ for ru in sorted(regions, key=len):
128
+ for rd in children[ru]:
129
+ message_order.append((ru, rd))
130
+ messages[ru, rd] = Factor.zeros(domain.project(rd))
131
+ messages[rd, ru] = Factor.zeros(domain.project(rd)) # only for hazan et al
132
+
133
+ return regions, cliques, messages, message_order, parents, children
134
+
135
+ _State = dict[tuple[Clique, Clique], Factor]
136
+
137
+ @functools.partial(jax.jit, static_argnames=['mesh', 'iters'])
138
+ def convex_generalized_belief_propagation(
139
+ potentials: CliqueVector,
140
+ total: float = 1,
141
+ state: _State | None = None,
142
+ mesh: jax.sharding.Mesh | None = None,
143
+ iters: int = 1,
144
+ damping: float = 0.5,
145
+ ) -> tuple[CliqueVector, _State]:
146
+ """Convex generalized belief propagation for approximmate marginal inference.
147
+
148
+ The algorithms implements the Algorithm 2 in our paper
149
+ ["Relaxed Marginal Consistency for Differentially Private Query Answering"](https://arxiv.org/pdf/2109.06153), which itself is based on the paper titled
150
+ ["Tightening Fractional Covering Upper Bounds on the Partition
151
+ Function for High-Order Region Graphs"](https://arxiv.org/pdf/1210.4881).
152
+
153
+ Args:
154
+ potentials: A CliqueVector object containing the potentials of the graphical model.
155
+ total: The total number of records in the dataset.
156
+ state: The state of the message passing algorithm (i.e., the messages). Useful when
157
+ calling this within an iterative procedure for warm starting purposes.
158
+ mesh: Specifies how the computation will be sharded across machines.
159
+ iters: The number of iterations to run the algorithm.
160
+ damping: The damping factor for the messages.
161
+
162
+ Returns:
163
+ A CliqueVector of pseudo-marginals for the cliques in the graphical model.
164
+ """
165
+ potentials = potentials.apply_sharding(mesh)
166
+ domain, cliques = potentials.domain, potentials.cliques
167
+ # We might need or want a sharding constraint on messages here
168
+ regions, cliques, messages, message_order, parents, children = build_graph(
169
+ domain, cliques
170
+ )
171
+ if state is not None:
172
+ messages = state
173
+
174
+ # Hardcode assumption that counting numbers are 1.0 for all regions.
175
+ pot = potentials.expand(regions)
176
+
177
+ cc = {}
178
+ for r in regions:
179
+ for p in parents[r]:
180
+ cc[p, r] = 1 / (1 + len(parents[r]))
181
+
182
+ for _ in range(iters):
183
+ new = {}
184
+ for r in regions:
185
+ for p in parents[r]:
186
+ new[p, r] = (
187
+ (
188
+ pot[p]
189
+ + sum(messages[c, p] for c in children[p] if c != r)
190
+ - sum(messages[p, p1] for p1 in parents[p])
191
+ )
192
+ .project(r, log=True)
193
+ .normalize(log=True)
194
+ .apply_sharding(mesh)
195
+ )
196
+
197
+ for r in regions:
198
+ for p in parents[r]:
199
+ new[r, p] = (
200
+ cc[p, r]
201
+ * (
202
+ pot[r]
203
+ + sum(messages[c, r] for c in children[r])
204
+ + sum(messages[p1, r] for p1 in parents[r])
205
+ )
206
+ - messages[p, r]
207
+ ).normalize(log=True).apply_sharding(mesh)
208
+
209
+ # Damping is not described in paper, but is needed to get convergence for dense graphs
210
+ rho = damping
211
+ for p in regions:
212
+ for r in children[p]:
213
+ messages[p, r] = rho * messages[p, r] + (1.0 - rho) * new[p, r]
214
+ messages[r, p] = rho * messages[r, p] + (1.0 - rho) * new[r, p]
215
+ mu = {}
216
+ for r in cliques:
217
+ mu[r] = (
218
+ (
219
+ pot[r]
220
+ + sum(messages[c, r] for c in children[r])
221
+ - sum(messages[r, p] for p in parents[r])
222
+ )
223
+ .normalize(total, log=True)
224
+ .exp()
225
+ .apply_sharding(mesh)
226
+ )
227
+
228
+ return CliqueVector(domain, cliques, mu), messages
@@ -0,0 +1,91 @@
1
+ """Defines callback mechanisms for monitoring optimization processes.
2
+
3
+ This module provides a `Callback` class that can be used to track and log
4
+ various metrics during iterative algorithms, such as those used in estimating
5
+ marginals. It logs loss values and other relevant statistics.
6
+ """
7
+ import attr
8
+ import jax
9
+ import pandas as pd
10
+
11
+ from . import marginal_loss
12
+ from .clique_vector import CliqueVector
13
+ from .factor import Projectable
14
+ from .marginal_loss import LinearMeasurement
15
+
16
+
17
+ def _pad(string: str, length: int):
18
+ """Pads a string with spaces on both sides to a target length."""
19
+ if len(string) > length:
20
+ return string[:length]
21
+ left_pad = (length - len(string)) // 2
22
+ right_pad = length - len(string) - left_pad
23
+ return " " * left_pad + string + " " * right_pad
24
+
25
+
26
+ @attr.dataclass
27
+ class Callback:
28
+ loss_fns: dict[str, marginal_loss.MarginalLossFn]
29
+ frequency: int = 50
30
+ # Internal state
31
+ _step: int = 0
32
+ _logs: list = attr.field(factory=list)
33
+
34
+ def __call__(self, marginals: CliqueVector):
35
+ if self._step == 0:
36
+ header = "|".join([_pad(x, 12) for x in ["step", *self.loss_fns.keys()]])
37
+ print(header)
38
+ print("=" * len(header))
39
+ if self._step % self.frequency == 0:
40
+ row = [self.loss_fns[key](marginals) for key in self.loss_fns]
41
+ self._logs.append([self._step] + row)
42
+ padded_step = str(self._step) + " " * (9 - len(str(self._step)))
43
+ print(padded_step, *[("%.6f" % v)[:6] for v in row], sep=" | ")
44
+ self._step += 1
45
+
46
+ @property
47
+ def summary(self):
48
+ return pd.DataFrame(
49
+ columns=["step"] + list(self.loss_fns.keys()), data=self._logs
50
+ ).astype(float)
51
+
52
+
53
+ def default(
54
+ measurements: list[LinearMeasurement],
55
+ data: Projectable | None = None,
56
+ frequency: int = 50,
57
+ ) -> Callback:
58
+ """Creates a default Callback with standard loss functions (L1/L2 Loss/Error, Primal Feas)."""
59
+ loss_fns = {}
60
+ # Measures distance between input marginals and noisy marginals.
61
+ loss_fns["L2 Loss"] = marginal_loss.from_linear_measurements(
62
+ measurements, norm="l2", normalize=True
63
+ )
64
+ loss_fns["L1 Loss"] = marginal_loss.from_linear_measurements(
65
+ measurements,
66
+ norm="l1",
67
+ normalize=True,
68
+ )
69
+
70
+ if data is not None:
71
+ # Measures distance between input marginals and true marginals.
72
+ ground_truth = [
73
+ LinearMeasurement(
74
+ M.query(data.project(M.clique)),
75
+ clique=M.clique,
76
+ stddev=1,
77
+ query=M.query,
78
+ )
79
+ for M in measurements
80
+ ]
81
+ loss_fns["L2 Error"] = marginal_loss.from_linear_measurements(
82
+ ground_truth, norm="l2", normalize=True
83
+ )
84
+ loss_fns["L1 Error"] = marginal_loss.from_linear_measurements(
85
+ ground_truth, norm="l1", normalize=True
86
+ )
87
+
88
+ loss_fns = {key: jax.jit(loss_fns[key].__call__) for key in loss_fns}
89
+ loss_fns["Primal Feas"] = jax.jit(marginal_loss.primal_feasibility)
90
+
91
+ return Callback(loss_fns, frequency)