remix-vi 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.
remix_vi-1.0.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Intelligent Systems
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,66 @@
1
+ Metadata-Version: 2.4
2
+ Name: remix-vi
3
+ Version: 1.0.0
4
+ Summary: Monte Carlo gradient estimation for finite mixture distributions
5
+ License-Expression: MIT
6
+ Requires-Python: >=3.10
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Requires-Dist: torch>=2.0
10
+ Provides-Extra: test
11
+ Requires-Dist: pytest>=8; extra == "test"
12
+ Dynamic: license-file
13
+
14
+ # ReMix
15
+
16
+ ReMix is a PyTorch library for Monte Carlo gradient estimation with finite
17
+ mixture distributions.
18
+
19
+ ## Install
20
+
21
+ After a release is published to a package index:
22
+
23
+ ```bash
24
+ python -m pip install remix-vi
25
+ ```
26
+
27
+ To build and install a wheel from a source checkout:
28
+
29
+ ```bash
30
+ python -m pip install build
31
+ python -m build
32
+ python -m pip install dist/remix_vi-1.0.0-py3-none-any.whl
33
+ ```
34
+
35
+ The wheel can be copied to another project or uploaded to a package index; the
36
+ consumer does not need this repository. The PyPI distribution is named
37
+ `remix-vi`, while its Python import package remains `remix`. ReMix requires
38
+ Python 3.10+ and PyTorch 2.0+.
39
+
40
+ ## Quick start
41
+
42
+ ```python
43
+ import torch
44
+ from torch.distributions import Normal
45
+
46
+ from remix import ELBOObjective, Mixture, ScoreFunction
47
+
48
+ components = [Normal(-2.0, 1.0), Normal(2.0, 1.0)]
49
+ target = Mixture(torch.tensor([0.2, 0.8]).log(), components)
50
+ logits = torch.nn.Parameter(torch.zeros(2))
51
+ optimizer = torch.optim.Adam([logits], lr=0.05)
52
+ estimator = ScoreFunction(n_samples=512)
53
+ objective = ELBOObjective(target.log_prob)
54
+
55
+ optimizer.zero_grad()
56
+ result = estimator.estimate(Mixture(logits, components), objective)
57
+ result.surrogate_loss.backward()
58
+ optimizer.step()
59
+ ```
60
+
61
+ The public API also includes `Stratified`, `Implicit`, and `PostStratified`.
62
+ The latter two currently require scalar-event components with differentiable
63
+ CDFs; `PostStratified` also requires differentiable inverse CDFs. `Stratified`
64
+ requires each component to support `rsample()`.
65
+
66
+ See the [API documentation](https://github.com/intsystems/remix/blob/master/docs/source/index.md).
@@ -0,0 +1,53 @@
1
+ # ReMix
2
+
3
+ ReMix is a PyTorch library for Monte Carlo gradient estimation with finite
4
+ mixture distributions.
5
+
6
+ ## Install
7
+
8
+ After a release is published to a package index:
9
+
10
+ ```bash
11
+ python -m pip install remix-vi
12
+ ```
13
+
14
+ To build and install a wheel from a source checkout:
15
+
16
+ ```bash
17
+ python -m pip install build
18
+ python -m build
19
+ python -m pip install dist/remix_vi-1.0.0-py3-none-any.whl
20
+ ```
21
+
22
+ The wheel can be copied to another project or uploaded to a package index; the
23
+ consumer does not need this repository. The PyPI distribution is named
24
+ `remix-vi`, while its Python import package remains `remix`. ReMix requires
25
+ Python 3.10+ and PyTorch 2.0+.
26
+
27
+ ## Quick start
28
+
29
+ ```python
30
+ import torch
31
+ from torch.distributions import Normal
32
+
33
+ from remix import ELBOObjective, Mixture, ScoreFunction
34
+
35
+ components = [Normal(-2.0, 1.0), Normal(2.0, 1.0)]
36
+ target = Mixture(torch.tensor([0.2, 0.8]).log(), components)
37
+ logits = torch.nn.Parameter(torch.zeros(2))
38
+ optimizer = torch.optim.Adam([logits], lr=0.05)
39
+ estimator = ScoreFunction(n_samples=512)
40
+ objective = ELBOObjective(target.log_prob)
41
+
42
+ optimizer.zero_grad()
43
+ result = estimator.estimate(Mixture(logits, components), objective)
44
+ result.surrogate_loss.backward()
45
+ optimizer.step()
46
+ ```
47
+
48
+ The public API also includes `Stratified`, `Implicit`, and `PostStratified`.
49
+ The latter two currently require scalar-event components with differentiable
50
+ CDFs; `PostStratified` also requires differentiable inverse CDFs. `Stratified`
51
+ requires each component to support `rsample()`.
52
+
53
+ See the [API documentation](https://github.com/intsystems/remix/blob/master/docs/source/index.md).
@@ -0,0 +1,26 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "remix-vi"
7
+ version = "1.0.0"
8
+ description = "Monte Carlo gradient estimation for finite mixture distributions"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ dynamic = ["dependencies"]
14
+
15
+ [project.optional-dependencies]
16
+ test = ["pytest>=8"]
17
+
18
+ [tool.setuptools]
19
+ package-dir = {"" = "src"}
20
+
21
+ [tool.setuptools.packages.find]
22
+ where = ["src"]
23
+ include = ["remix*"]
24
+
25
+ [tool.setuptools.dynamic]
26
+ dependencies = {file = ["src/requirements.txt"]}
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,24 @@
1
+ """Monte Carlo gradient estimation for finite mixtures."""
2
+
3
+ from .distributions import Mixture
4
+ from .objectives import ELBOObjective
5
+ from .estimators import (
6
+ EstimateResult,
7
+ GradientEstimator,
8
+ Implicit,
9
+ PostStratified,
10
+ ScoreFunction,
11
+ Stratified,
12
+ )
13
+
14
+ __version__ = "1.0.0"
15
+ __all__ = [
16
+ "Mixture",
17
+ "ELBOObjective",
18
+ "EstimateResult",
19
+ "GradientEstimator",
20
+ "ScoreFunction",
21
+ "Stratified",
22
+ "Implicit",
23
+ "PostStratified",
24
+ ]
@@ -0,0 +1,127 @@
1
+ """Finite mixtures with arbitrary compatible component families."""
2
+
3
+ from collections.abc import Sequence
4
+
5
+ import torch
6
+ from torch import Tensor
7
+ from torch.distributions import (
8
+ Categorical,
9
+ Distribution,
10
+ Independent,
11
+ MixtureSameFamily,
12
+ )
13
+
14
+ # Alternative parameterisations of one and the same distribution. A
15
+ # constructor accepts only one of them, so ``detach_distribution`` keeps the
16
+ # first name of a group that it finds on the instance.
17
+ _EXCLUSIVE_PARAM_GROUPS = (
18
+ ("logits", "probs"),
19
+ ("scale_tril", "covariance_matrix", "precision_matrix"),
20
+ )
21
+
22
+
23
+ def detach_distribution(dist: Distribution) -> Distribution:
24
+ """Rebuild ``dist`` with all parameters cut from the autograd graph.
25
+
26
+ The result has the same density, but no gradient flows into its
27
+ parameters. A sample ``z`` passed to its ``log_prob`` keeps its own
28
+ gradient, which is what the Sticking-the-Landing trick needs.
29
+
30
+ Supports ``Independent``, ``MixtureSameFamily``, any distribution that
31
+ defines its own ``detach()`` and every distribution built from the
32
+ tensors listed in ``arg_constraints`` (``Normal``, ``StudentT``,
33
+ ``Laplace``, ``MultivariateNormal``, ``Categorical``, ...).
34
+ """
35
+ # A distribution may know how to detach itself (custom components).
36
+ if hasattr(dist, "detach") and callable(dist.detach):
37
+ return dist.detach()
38
+
39
+ validate_args = dist._validate_args
40
+
41
+ # Wrappers: detach what they wrap, then rebuild the wrapper itself.
42
+ if isinstance(dist, Independent):
43
+ return Independent(
44
+ detach_distribution(dist.base_dist),
45
+ dist.reinterpreted_batch_ndims,
46
+ validate_args=validate_args,
47
+ )
48
+ if isinstance(dist, MixtureSameFamily):
49
+ return MixtureSameFamily(
50
+ detach_distribution(dist.mixture_distribution),
51
+ detach_distribution(dist.component_distribution),
52
+ validate_args=validate_args,
53
+ )
54
+
55
+ # Plain distributions: take the parameters stored on the instance. A
56
+ # lazily computed alternative (``probs`` next to ``logits``) may be
57
+ # cached there as well, so only one name per exclusive group is kept.
58
+ names = [
59
+ name
60
+ for name in getattr(dist, "arg_constraints", {})
61
+ if name in dist.__dict__
62
+ ]
63
+ for group in _EXCLUSIVE_PARAM_GROUPS:
64
+ present = [name for name in group if name in names]
65
+ for redundant in present[1:]:
66
+ names.remove(redundant)
67
+ if not names:
68
+ raise NotImplementedError(
69
+ f"Cannot detach {type(dist).__name__}: "
70
+ "wrap it or give it a detach() method."
71
+ )
72
+
73
+ params = {name: getattr(dist, name).detach() for name in names}
74
+ return type(dist)(**params, validate_args=validate_args)
75
+
76
+
77
+ class Mixture:
78
+ """An unbatched mixture, components share event shape and base measure."""
79
+
80
+ def __init__(self, logits: Tensor, components: Sequence[Distribution]):
81
+ self.components = tuple(components)
82
+
83
+ if logits.ndim != 1 or logits.numel() != len(self.components) or not self.components:
84
+ raise ValueError("Provide one logit per component in a nonempty mixture.")
85
+
86
+ self.event_shape = self.components[0].event_shape
87
+
88
+ if any(c.batch_shape or c.event_shape != self.event_shape for c in self.components):
89
+ raise ValueError("Components must be unbatched and have identical event shapes.")
90
+
91
+ self.logits = logits
92
+ self.mixing = Categorical(logits=logits)
93
+
94
+ def sample(self, sample_shape: tuple) -> Tensor:
95
+ sample_shape = torch.Size(sample_shape)
96
+ count = sample_shape.numel()
97
+
98
+ with torch.no_grad():
99
+ indices = self.mixing.sample((count,))
100
+ samples = torch.stack([c.sample((count,)) for c in self.components], dim=1)
101
+ selected = samples[torch.arange(count, device=indices.device), indices]
102
+
103
+ return selected.reshape(sample_shape + self.event_shape)
104
+
105
+ def _log_joint(self, z: Tensor) -> Tensor:
106
+ log_probs = torch.stack([c.log_prob(z) for c in self.components], dim=-1)
107
+ return self.mixing.logits + log_probs
108
+
109
+ def log_prob(self, z: Tensor) -> Tensor:
110
+ return torch.logsumexp(self._log_joint(z), dim=-1)
111
+
112
+ def responsibilities(self, z: Tensor) -> Tensor:
113
+ """Return posterior component probabilities for each sample."""
114
+ return self._log_joint(z).softmax(dim=-1)
115
+
116
+ def detach(self) -> "Mixture":
117
+ """Return a copy with the same density and parameters without grad.
118
+
119
+ Gradients still flow through the argument ``z`` of ``log_prob``, but
120
+ not into the weights and component parameters (the "stop gradient"
121
+ of STL).
122
+ """
123
+ return Mixture(
124
+ self.logits.detach(),
125
+ [detach_distribution(c) for c in self.components],
126
+ )
127
+
@@ -0,0 +1,277 @@
1
+ """Gradient estimators returning a minimizable surrogate loss."""
2
+
3
+ from abc import ABC, abstractmethod
4
+ from dataclasses import dataclass
5
+
6
+ import torch
7
+ from torch import Tensor
8
+
9
+ from .distributions import Mixture
10
+ from .objectives import ELBOObjective
11
+
12
+
13
+ @dataclass
14
+ class EstimateResult:
15
+ """Output of a gradient estimator.
16
+
17
+ Attributes:
18
+ value: Detached Monte Carlo estimate of the objective, for logging.
19
+ surrogate_loss: Scalar whose gradient is the negative gradient
20
+ estimate; call `backward()` on it and step a minimizing optimizer.
21
+ """
22
+
23
+ value: Tensor
24
+ surrogate_loss: Tensor
25
+
26
+
27
+ class GradientEstimator(ABC):
28
+ """Base class for Monte Carlo gradient estimators.
29
+
30
+ Args:
31
+ n_samples: Number of samples drawn per `estimate` call.
32
+
33
+ Raises:
34
+ ValueError: If `n_samples` is not a positive integer.
35
+ """
36
+
37
+ def __init__(self, n_samples: int = 1):
38
+ if isinstance(n_samples, bool) or not isinstance(n_samples, int) or n_samples < 1:
39
+ raise ValueError("n_samples must be a positive integer.")
40
+
41
+ self.n_samples = n_samples
42
+
43
+ @abstractmethod
44
+ def estimate(self, q: Mixture, objective: ELBOObjective) -> EstimateResult:
45
+ """Estimate an objective and construct its negative gradient surrogate.
46
+
47
+ Args:
48
+ q: Variational mixture whose parameters receive gradients.
49
+ objective: Objective to maximize.
50
+
51
+ Returns:
52
+ The objective estimate and the surrogate loss.
53
+ """
54
+
55
+
56
+ class ScoreFunction(GradientEstimator):
57
+ """REINFORCE algorithm with a fixed, sample-independent baseline.
58
+
59
+ Uses `grad E_q[f] = E_q[(f(z) - b) grad log q(z) + grad f(z)]` with samples
60
+ detached from the parameters, so it works with non-reparameterizable
61
+ components.
62
+
63
+ Args:
64
+ n_samples: Number of samples drawn per `estimate` call.
65
+ baseline: Constant `b` subtracted from the objective values to reduce
66
+ variance.
67
+
68
+ Example:
69
+ >>> import torch
70
+ >>> from torch.distributions import Normal
71
+ >>> from remix import ELBOObjective, Mixture
72
+ >>> components = [Normal(-2.0, 1.0), Normal(2.0, 1.0)]
73
+ >>> target = Mixture(torch.tensor([0.2, 0.8]).log(), components)
74
+ >>> logits = torch.zeros(2, requires_grad=True)
75
+ >>> estimator = ScoreFunction(n_samples=512)
76
+ >>> objective = ELBOObjective(target.log_prob)
77
+ >>> result = estimator.estimate(Mixture(logits, components), objective)
78
+ >>> result.surrogate_loss.backward()
79
+ """
80
+
81
+ def __init__(self, n_samples: int = 1, baseline: float = 0.0):
82
+ super().__init__(n_samples)
83
+ self.baseline = float(baseline)
84
+
85
+ def estimate(self, q: Mixture, objective: ELBOObjective) -> EstimateResult:
86
+ """Estimate the objective with the score-function surrogate.
87
+
88
+ Args:
89
+ q: Variational mixture whose parameters receive gradients.
90
+ objective: Objective to maximize.
91
+
92
+ Returns:
93
+ The objective estimate and the surrogate loss.
94
+
95
+ Raises:
96
+ TypeError: If `q` is not a `Mixture`.
97
+ """
98
+ if not isinstance(q, Mixture):
99
+ raise TypeError("q must be a Mixture.")
100
+
101
+ z = q.sample(torch.Size([self.n_samples])).detach()
102
+ log_q = q.log_prob(z)
103
+ values = objective.evaluate(q, z)
104
+
105
+ surrogate = (values.detach() - self.baseline) * log_q + values
106
+ return EstimateResult(values.detach().mean(), -surrogate.mean())
107
+
108
+
109
+ class Stratified(GradientEstimator):
110
+ """Pathwise gradient estimator with a fixed sample count per component.
111
+
112
+ Draws independent reparameterized samples from each component and weights
113
+ the component means by the mixture probabilities. With one sample per
114
+ component this is Estimator 1 of Burroni and Sheldon (2026). Setting
115
+ `stl=True` on the objective gives their Sticking-the-Landing variant.
116
+
117
+ Args:
118
+ n_samples: Number of samples per component per `estimate` call.
119
+ """
120
+
121
+ def estimate(self, q: Mixture, objective: ELBOObjective) -> EstimateResult:
122
+ """Estimate the objective by stratifying over the mixture components.
123
+
124
+ Args:
125
+ q: Variational mixture whose parameters receive gradients.
126
+ objective: Objective to maximize.
127
+
128
+ Returns:
129
+ The objective estimate and its negative as the surrogate loss.
130
+
131
+ Raises:
132
+ TypeError: If `q` is not a `Mixture` or a component cannot be
133
+ reparameterized.
134
+ """
135
+ if not isinstance(q, Mixture):
136
+ raise TypeError("q must be a Mixture.")
137
+ if any(not component.has_rsample for component in q.components):
138
+ raise TypeError("Stratified requires all components to support rsample.")
139
+
140
+ sample_shape = torch.Size([self.n_samples])
141
+ z = torch.cat([component.rsample(sample_shape) for component in q.components])
142
+ values = objective.evaluate(q, z).reshape(len(q.components), self.n_samples)
143
+ estimate = (q.mixing.probs * values.mean(dim=1)).sum()
144
+ return EstimateResult(estimate.detach(), -estimate)
145
+
146
+
147
+ def _validate_scalar_continuous_mixture(q: Mixture, estimator: str) -> None:
148
+ if q.event_shape:
149
+ raise TypeError(f"{estimator} currently requires scalar-event components.")
150
+ if any(not component.has_rsample for component in q.components):
151
+ raise TypeError(f"{estimator} requires continuous components with rsample().")
152
+
153
+
154
+ def _sample_with_input_gradient(
155
+ q: Mixture, objective: ELBOObjective, n_samples: int
156
+ ) -> tuple[Tensor, Tensor, Tensor]:
157
+ z = q.sample(torch.Size([n_samples])).detach().requires_grad_()
158
+ values = objective.evaluate(q, z)
159
+ if values.requires_grad:
160
+ (input_gradient,) = torch.autograd.grad(
161
+ values.sum(), z, retain_graph=True, allow_unused=True
162
+ )
163
+ else:
164
+ input_gradient = None
165
+ if input_gradient is None:
166
+ input_gradient = torch.zeros_like(z)
167
+ return z, values, input_gradient.detach()
168
+
169
+
170
+ class Implicit(GradientEstimator):
171
+ """Implicit reparameterization estimator for scalar continuous mixtures.
172
+
173
+ The mixture CDF defines a scalar rank map. Its parameter derivative gives
174
+ the pathwise sampling term without differentiating through the sampled
175
+ component label. Each component must provide a differentiable ``cdf``.
176
+
177
+ Args:
178
+ n_samples: Number of mixture samples per `estimate` call.
179
+ """
180
+
181
+ def estimate(self, q: Mixture, objective: ELBOObjective) -> EstimateResult:
182
+ """Estimate the objective using the mixture CDF rank map.
183
+
184
+ Raises:
185
+ TypeError: If the mixture is not scalar/continuous or its
186
+ components do not implement ``cdf``.
187
+ FloatingPointError: If inverse-density scaling is not finite.
188
+ """
189
+ if not isinstance(q, Mixture):
190
+ raise TypeError("q must be a Mixture.")
191
+ _validate_scalar_continuous_mixture(q, type(self).__name__)
192
+
193
+ z, values, input_gradient = _sample_with_input_gradient(
194
+ q, objective, self.n_samples
195
+ )
196
+ try:
197
+ component_cdfs = torch.stack(
198
+ [component.cdf(z.detach()) for component in q.components],
199
+ dim=-1,
200
+ )
201
+ except NotImplementedError as exc:
202
+ raise TypeError(
203
+ "Implicit requires every component to implement cdf()."
204
+ ) from exc
205
+
206
+ mixture_cdf = (q.mixing.probs * component_cdfs).sum(dim=-1)
207
+ inverse_density = torch.exp(-q.log_prob(z.detach()).detach())
208
+ if not torch.isfinite(inverse_density).all():
209
+ raise FloatingPointError(
210
+ "Implicit encountered a non-finite inverse mixture density."
211
+ )
212
+
213
+ correction = -(
214
+ input_gradient * inverse_density * mixture_cdf
215
+ ).mean()
216
+ surrogate = values.mean() + correction - correction.detach()
217
+ return EstimateResult(values.detach().mean(), -surrogate)
218
+
219
+
220
+ class PostStratified(GradientEstimator):
221
+ """Single-sample continuous-transport estimator for scalar mixtures.
222
+
223
+ The estimator averages the component-label gradient conditional on each
224
+ sampled point, using component responsibilities and inverse CDF maps.
225
+ Components must provide differentiable ``cdf`` and ``icdf`` methods.
226
+
227
+ Args:
228
+ n_samples: Number of mixture samples per `estimate` call. The default
229
+ of one is the single-sample estimator.
230
+ """
231
+
232
+ def estimate(self, q: Mixture, objective: ELBOObjective) -> EstimateResult:
233
+ """Estimate the objective using post-stratified component transports.
234
+
235
+ Raises:
236
+ TypeError: If the mixture is not scalar/continuous or its
237
+ components do not implement ``cdf`` and ``icdf``.
238
+ FloatingPointError: If a component inverse CDF returns a
239
+ non-finite transport point.
240
+ """
241
+ if not isinstance(q, Mixture):
242
+ raise TypeError("q must be a Mixture.")
243
+ _validate_scalar_continuous_mixture(q, type(self).__name__)
244
+
245
+ z, values, input_gradient = _sample_with_input_gradient(
246
+ q, objective, self.n_samples
247
+ )
248
+ transported_points = []
249
+ try:
250
+ for component in q.components:
251
+ cdf = component.cdf(z.detach())
252
+ transported_points.append(component.icdf(cdf.detach()))
253
+ except NotImplementedError as exc:
254
+ raise TypeError(
255
+ "PostStratified requires every component to implement "
256
+ "cdf() and icdf()."
257
+ ) from exc
258
+
259
+ transported = torch.stack(transported_points, dim=-1)
260
+ if not torch.isfinite(transported).all():
261
+ raise FloatingPointError(
262
+ "PostStratified encountered a non-finite inverse-CDF point."
263
+ )
264
+
265
+ responsibilities = q.responsibilities(z.detach()).detach()
266
+ component_samples = (
267
+ input_gradient.unsqueeze(-1) * responsibilities * transported
268
+ ).sum(dim=-1).mean()
269
+ logits_gradient = (
270
+ values.detach().unsqueeze(-1)
271
+ * (responsibilities - q.mixing.probs.detach())
272
+ ).mean(dim=0)
273
+ logits_score = (q.logits * logits_gradient).sum()
274
+
275
+ correction = component_samples + logits_score
276
+ surrogate = values.mean() + correction - correction.detach()
277
+ return EstimateResult(values.detach().mean(), -surrogate)
@@ -0,0 +1,53 @@
1
+ """Objectives using the public sampling and density interface."""
2
+
3
+ from typing import Callable
4
+
5
+ from torch import Tensor
6
+
7
+ from .distributions import Mixture
8
+
9
+
10
+ class ELBOObjective:
11
+ """ELBO integrand, log_joint and log_prob must have identical shapes.
12
+
13
+ With ``stl=True`` the Sticking-the-Landing trick of Roeder et al. (2017)
14
+ is applied: ``log q(z)`` is evaluated with the parameters of ``q``
15
+ detached ("stop gradient"). The values of the integrand are unchanged,
16
+ but its explicit dependence on the parameters of ``q`` (a score term
17
+ with zero mean) disappears from the gradient. The gradient that flows
18
+ through the sample ``z`` itself is kept, so a reparameterised ``z``
19
+ still produces the pathwise gradient, and gradients w.r.t. parameters
20
+ of ``log_joint`` are unaffected. Estimators remain unbiased; the
21
+ variance goes to zero as ``q`` approaches the true posterior.
22
+
23
+ With ``stl=True`` the Sticking-the-Landing trick of Roeder et al. (2017)
24
+ is applied: ``log q(z)`` is evaluated with the parameters of ``q``
25
+ detached ("stop gradient"). The values of the integrand are unchanged, but
26
+ its explicit dependence on the parameters of ``q`` (a score term with zero
27
+ mean) disappears from the gradient. The gradient that flows through the
28
+ sample ``z`` itself is kept, so a reparameterised ``z`` still produces the
29
+ pathwise gradient, and gradients w.r.t. parameters of ``log_joint`` are
30
+ unaffected. Estimators remain unbiased; the variance goes to zero as ``q``
31
+ approaches the true posterior.
32
+ """
33
+
34
+ def __init__(
35
+ self,
36
+ log_joint: Callable[[Tensor], Tensor],
37
+ stl: bool = False,
38
+ ):
39
+ self.log_joint = log_joint
40
+ self.stl = bool(stl)
41
+
42
+ def evaluate(self, q: Mixture, z: Tensor) -> Tensor:
43
+ # With STL the density is evaluated by a copy of q without gradient
44
+ # into its parameters; only the path through z is differentiable.
45
+ log_q = (q.detach() if self.stl else q).log_prob(z)
46
+ log_p = self.log_joint(z)
47
+ if log_p.shape != log_q.shape:
48
+ raise ValueError(
49
+ "log_joint and log_prob must have identical shapes, "
50
+ "use Independent for vector events."
51
+ )
52
+ return log_p - log_q
53
+
@@ -0,0 +1,66 @@
1
+ Metadata-Version: 2.4
2
+ Name: remix-vi
3
+ Version: 1.0.0
4
+ Summary: Monte Carlo gradient estimation for finite mixture distributions
5
+ License-Expression: MIT
6
+ Requires-Python: >=3.10
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Requires-Dist: torch>=2.0
10
+ Provides-Extra: test
11
+ Requires-Dist: pytest>=8; extra == "test"
12
+ Dynamic: license-file
13
+
14
+ # ReMix
15
+
16
+ ReMix is a PyTorch library for Monte Carlo gradient estimation with finite
17
+ mixture distributions.
18
+
19
+ ## Install
20
+
21
+ After a release is published to a package index:
22
+
23
+ ```bash
24
+ python -m pip install remix-vi
25
+ ```
26
+
27
+ To build and install a wheel from a source checkout:
28
+
29
+ ```bash
30
+ python -m pip install build
31
+ python -m build
32
+ python -m pip install dist/remix_vi-1.0.0-py3-none-any.whl
33
+ ```
34
+
35
+ The wheel can be copied to another project or uploaded to a package index; the
36
+ consumer does not need this repository. The PyPI distribution is named
37
+ `remix-vi`, while its Python import package remains `remix`. ReMix requires
38
+ Python 3.10+ and PyTorch 2.0+.
39
+
40
+ ## Quick start
41
+
42
+ ```python
43
+ import torch
44
+ from torch.distributions import Normal
45
+
46
+ from remix import ELBOObjective, Mixture, ScoreFunction
47
+
48
+ components = [Normal(-2.0, 1.0), Normal(2.0, 1.0)]
49
+ target = Mixture(torch.tensor([0.2, 0.8]).log(), components)
50
+ logits = torch.nn.Parameter(torch.zeros(2))
51
+ optimizer = torch.optim.Adam([logits], lr=0.05)
52
+ estimator = ScoreFunction(n_samples=512)
53
+ objective = ELBOObjective(target.log_prob)
54
+
55
+ optimizer.zero_grad()
56
+ result = estimator.estimate(Mixture(logits, components), objective)
57
+ result.surrogate_loss.backward()
58
+ optimizer.step()
59
+ ```
60
+
61
+ The public API also includes `Stratified`, `Implicit`, and `PostStratified`.
62
+ The latter two currently require scalar-event components with differentiable
63
+ CDFs; `PostStratified` also requires differentiable inverse CDFs. `Stratified`
64
+ requires each component to support `rsample()`.
65
+
66
+ See the [API documentation](https://github.com/intsystems/remix/blob/master/docs/source/index.md).
@@ -0,0 +1,15 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/requirements.txt
5
+ src/remix/__init__.py
6
+ src/remix/distributions.py
7
+ src/remix/estimators.py
8
+ src/remix/objectives.py
9
+ src/remix_vi.egg-info/PKG-INFO
10
+ src/remix_vi.egg-info/SOURCES.txt
11
+ src/remix_vi.egg-info/dependency_links.txt
12
+ src/remix_vi.egg-info/requires.txt
13
+ src/remix_vi.egg-info/top_level.txt
14
+ tests/test_pathwise_estimators.py
15
+ tests/test_stl.py
@@ -0,0 +1,4 @@
1
+ torch>=2.0
2
+
3
+ [test]
4
+ pytest>=8
@@ -0,0 +1 @@
1
+ remix
@@ -0,0 +1 @@
1
+ torch>=2.0
@@ -0,0 +1,108 @@
1
+ import pytest
2
+ import torch
3
+ from torch.distributions import Independent, Normal
4
+
5
+ from remix import (
6
+ ELBOObjective,
7
+ Implicit,
8
+ Mixture,
9
+ PostStratified,
10
+ ScoreFunction,
11
+ Stratified,
12
+ )
13
+
14
+
15
+ DTYPE = torch.float64
16
+
17
+
18
+ @pytest.mark.parametrize(
19
+ "estimator_type",
20
+ [ScoreFunction, Stratified, Implicit, PostStratified],
21
+ )
22
+ def test_all_estimators_share_the_public_interface(estimator_type):
23
+ logits = torch.zeros(2, dtype=DTYPE, requires_grad=True)
24
+ q = Mixture(
25
+ logits,
26
+ [
27
+ Normal(torch.tensor(-1.0, dtype=DTYPE), torch.tensor(1.0, dtype=DTYPE)),
28
+ Normal(torch.tensor(1.0, dtype=DTYPE), torch.tensor(1.0, dtype=DTYPE)),
29
+ ],
30
+ )
31
+ objective = ELBOObjective(Normal(0.0, 1.0).log_prob)
32
+
33
+ result = estimator_type(n_samples=4).estimate(q, objective)
34
+
35
+ assert result.value.shape == result.surrogate_loss.shape == ()
36
+ assert not result.value.requires_grad
37
+ result.surrogate_loss.backward()
38
+ assert logits.grad is not None
39
+ assert torch.isfinite(logits.grad).all()
40
+
41
+
42
+ @pytest.mark.parametrize("estimator_type", [Implicit, PostStratified])
43
+ def test_scalar_normal_gradient_matches_exact_elbo(estimator_type):
44
+ torch.manual_seed(4)
45
+ loc = torch.tensor(0.7, dtype=DTYPE, requires_grad=True)
46
+ scale = torch.tensor(1.3, dtype=DTYPE, requires_grad=True)
47
+ logits = torch.zeros(1, dtype=DTYPE, requires_grad=True)
48
+ q = Mixture(logits, [Normal(loc, scale)])
49
+ target = Normal(torch.tensor(0.0, dtype=DTYPE), torch.tensor(1.0, dtype=DTYPE))
50
+ result = estimator_type(n_samples=8192).estimate(
51
+ q, ELBOObjective(target.log_prob)
52
+ )
53
+
54
+ result.surrogate_loss.backward()
55
+
56
+ assert torch.allclose(loc.grad, loc.detach(), atol=0.04, rtol=0.0)
57
+ expected_scale_grad = scale.detach() - scale.detach().reciprocal()
58
+ assert torch.allclose(scale.grad, expected_scale_grad, atol=0.04, rtol=0.0)
59
+ assert result.value.shape == result.surrogate_loss.shape == ()
60
+ assert torch.isfinite(result.value)
61
+ assert torch.isfinite(result.surrogate_loss)
62
+
63
+
64
+ @pytest.mark.parametrize("estimator_type", [Implicit, PostStratified])
65
+ def test_estimators_reject_vector_events(estimator_type):
66
+ q = Mixture(
67
+ torch.zeros(1, dtype=DTYPE),
68
+ [
69
+ Independent(
70
+ Normal(torch.zeros(2, dtype=DTYPE), torch.ones(2, dtype=DTYPE)),
71
+ 1,
72
+ )
73
+ ],
74
+ )
75
+ objective = ELBOObjective(lambda z: -z.square().sum(dim=-1))
76
+
77
+ with pytest.raises(TypeError, match="scalar-event"):
78
+ estimator_type().estimate(q, objective)
79
+
80
+
81
+ @pytest.mark.parametrize("estimator_type", [Implicit, PostStratified])
82
+ def test_mixture_logit_gradient_matches_quadrature(estimator_type):
83
+ logits = torch.tensor([0.2, -0.1], dtype=DTYPE, requires_grad=True)
84
+ components = [
85
+ Normal(torch.tensor(-1.0, dtype=DTYPE), torch.tensor(0.8, dtype=DTYPE)),
86
+ Normal(torch.tensor(1.2, dtype=DTYPE), torch.tensor(1.1, dtype=DTYPE)),
87
+ ]
88
+ target = Normal(torch.tensor(0.3, dtype=DTYPE), torch.tensor(1.2, dtype=DTYPE))
89
+ objective = ELBOObjective(target.log_prob)
90
+
91
+ q = Mixture(logits, components)
92
+ grid = torch.linspace(-10.0, 10.0, 20001, dtype=DTYPE)
93
+ log_q = q.log_prob(grid)
94
+ exact_elbo = torch.trapz(
95
+ log_q.exp() * (target.log_prob(grid) - log_q), grid
96
+ )
97
+ (exact_gradient,) = torch.autograd.grad(exact_elbo, logits)
98
+
99
+ torch.manual_seed(7)
100
+ q = Mixture(logits, components)
101
+ result = estimator_type(n_samples=4096).estimate(q, objective)
102
+ (estimated_loss_gradient,) = torch.autograd.grad(
103
+ result.surrogate_loss, logits
104
+ )
105
+
106
+ assert torch.allclose(
107
+ estimated_loss_gradient, -exact_gradient, atol=0.06, rtol=0.0
108
+ )
@@ -0,0 +1,332 @@
1
+ """Tests of the Sticking-the-Landing (STL) trick.
2
+
3
+ Covers ``detach_distribution`` / ``Mixture.detach``,
4
+ ``ELBOObjective(stl=True)`` and ``ScoreFunction`` used together with it.
5
+ """
6
+
7
+ import pytest
8
+ import torch
9
+ from torch.distributions import (
10
+ Categorical,
11
+ Distribution,
12
+ Independent,
13
+ MixtureSameFamily,
14
+ MultivariateNormal,
15
+ Normal,
16
+ StudentT,
17
+ )
18
+
19
+ from remix import ELBOObjective, EstimateResult, Mixture, ScoreFunction
20
+ from remix.distributions import detach_distribution
21
+
22
+ DTYPE = torch.float64
23
+
24
+
25
+ def make_q(logits, locs, log_scales):
26
+ """1-D Gaussian mixture; ``locs`` and ``log_scales`` have shape (K, 1)."""
27
+ components = [
28
+ Independent(Normal(locs[k], log_scales[k].exp()), 1)
29
+ for k in range(len(logits))
30
+ ]
31
+ return Mixture(logits, components)
32
+
33
+
34
+ def make_params(seed=0, k=3):
35
+ g = torch.Generator().manual_seed(seed)
36
+ logits = torch.randn(k, generator=g, dtype=DTYPE)
37
+ locs = torch.randn(k, 1, generator=g, dtype=DTYPE)
38
+ log_scales = 0.2 * torch.randn(k, 1, generator=g, dtype=DTYPE)
39
+ return [t.requires_grad_() for t in (logits, locs, log_scales)]
40
+
41
+
42
+ @pytest.fixture
43
+ def target():
44
+ """Fixed target density p(z): a two-component 1-D mixture."""
45
+ logits = torch.tensor([0.3, -0.2], dtype=DTYPE)
46
+ locs = torch.tensor([[-1.5], [1.2]], dtype=DTYPE)
47
+ log_scales = torch.log(torch.tensor([[0.8], [1.1]], dtype=DTYPE))
48
+ return make_q(logits, locs, log_scales)
49
+
50
+
51
+ def exact_neg_elbo_grad(params, target):
52
+ """Gradient of -ELBO computed by quadrature on a fine 1-D grid."""
53
+ q = make_q(*params)
54
+ grid = torch.linspace(-15.0, 15.0, 30001, dtype=DTYPE).unsqueeze(-1)
55
+ log_q, log_p = q.log_prob(grid), target.log_prob(grid)
56
+ neg_elbo = -torch.trapz(log_q.exp() * (log_p - log_q), grid.squeeze(-1))
57
+ grads = torch.autograd.grad(neg_elbo, params)
58
+ return torch.cat([g.reshape(-1) for g in grads])
59
+
60
+
61
+ def gradient_moments(loss_fn, params, n_repeats):
62
+ """Monte Carlo mean and variance of the gradient of ``loss_fn()``."""
63
+ draws = []
64
+ for _ in range(n_repeats):
65
+ grads = torch.autograd.grad(loss_fn(), params, allow_unused=True)
66
+ draws.append(
67
+ torch.cat(
68
+ [
69
+ (torch.zeros_like(p) if g is None else g).reshape(-1)
70
+ for p, g in zip(params, grads)
71
+ ]
72
+ )
73
+ )
74
+ stacked = torch.stack(draws)
75
+ return stacked.mean(0), stacked.var(0, unbiased=True)
76
+
77
+
78
+ # --------------------------------------------------------------------------
79
+ # detach_distribution
80
+ # --------------------------------------------------------------------------
81
+ def _grad_blocked(dist, params, z):
82
+ """log_prob is unchanged, depends on no parameter, and keeps its z-path."""
83
+ detached = detach_distribution(dist)
84
+ z = z.clone().requires_grad_()
85
+ out = detached.log_prob(z)
86
+ assert torch.allclose(out, dist.log_prob(z))
87
+ grads = torch.autograd.grad(
88
+ out.sum(), [z] + list(params), allow_unused=True
89
+ )
90
+ assert grads[0].abs().sum() > 0
91
+ assert all(g is None for g in grads[1:])
92
+
93
+
94
+ def test_detach_normal_independent():
95
+ loc = torch.zeros(2, dtype=DTYPE, requires_grad=True)
96
+ scale = torch.ones(2, dtype=DTYPE, requires_grad=True)
97
+ dist = Independent(Normal(loc, scale), 1)
98
+ _grad_blocked(dist, [loc, scale], torch.randn(5, 2, dtype=DTYPE))
99
+
100
+
101
+ def test_detach_student_t_heterogeneous_family():
102
+ df = torch.tensor([4.0], dtype=DTYPE, requires_grad=True)
103
+ loc = torch.zeros(1, dtype=DTYPE, requires_grad=True)
104
+ scale = torch.ones(1, dtype=DTYPE, requires_grad=True)
105
+ dist = Independent(StudentT(df, loc, scale), 1)
106
+ _grad_blocked(dist, [df, loc, scale], torch.randn(5, 1, dtype=DTYPE))
107
+
108
+
109
+ def test_detach_multivariate_normal_covariance_parameterisation():
110
+ loc = torch.zeros(2, dtype=DTYPE, requires_grad=True)
111
+ cov = (2.0 * torch.eye(2, dtype=DTYPE)).requires_grad_()
112
+ dist = MultivariateNormal(loc, covariance_matrix=cov)
113
+ _grad_blocked(dist, [loc, cov], torch.randn(5, 2, dtype=DTYPE))
114
+
115
+
116
+ def test_detach_mixture_same_family():
117
+ logits = torch.randn(3, dtype=DTYPE, requires_grad=True)
118
+ loc = torch.randn(3, 1, dtype=DTYPE, requires_grad=True)
119
+ dist = MixtureSameFamily(
120
+ Categorical(logits=logits),
121
+ Independent(Normal(loc, torch.ones(3, 1, dtype=DTYPE)), 1),
122
+ )
123
+ _grad_blocked(dist, [logits, loc], torch.randn(5, 1, dtype=DTYPE))
124
+
125
+
126
+ def test_detach_categorical_with_both_parameterisations_cached():
127
+ logits = torch.randn(4, dtype=DTYPE, requires_grad=True)
128
+ cat = Categorical(logits=logits)
129
+ _ = cat.probs # caches probs next to logits
130
+ detached = detach_distribution(cat)
131
+ assert torch.allclose(detached.probs, cat.probs)
132
+ assert not detached.probs.requires_grad
133
+
134
+
135
+ def test_detach_uses_custom_detach_method():
136
+ class Custom(Distribution):
137
+ arg_constraints = {}
138
+
139
+ def detach(self):
140
+ return "custom"
141
+
142
+ assert detach_distribution(Custom(validate_args=False)) == "custom"
143
+
144
+
145
+ def test_detach_unsupported_distribution_raises():
146
+ class Opaque(Distribution):
147
+ arg_constraints = {}
148
+
149
+ with pytest.raises(NotImplementedError):
150
+ detach_distribution(Opaque(validate_args=False))
151
+
152
+
153
+ # --------------------------------------------------------------------------
154
+ # Mixture.detach
155
+ # --------------------------------------------------------------------------
156
+ def test_mixture_detach_keeps_density_and_blocks_parameter_gradients():
157
+ params = make_params()
158
+ q = make_q(*params)
159
+ qd = q.detach()
160
+ z = torch.randn(7, 1, dtype=DTYPE)
161
+
162
+ assert isinstance(qd, Mixture) and qd is not q
163
+ assert torch.allclose(qd.log_prob(z), q.log_prob(z))
164
+ assert torch.allclose(qd.responsibilities(z), q.responsibilities(z))
165
+ assert not qd.log_prob(z).requires_grad
166
+ assert q.log_prob(z).requires_grad # the original is untouched
167
+
168
+
169
+ def test_mixture_detach_supports_mixed_component_families():
170
+ logits = torch.zeros(2, dtype=DTYPE, requires_grad=True)
171
+ loc = torch.zeros(1, dtype=DTYPE, requires_grad=True)
172
+ ones = torch.ones(1, dtype=DTYPE)
173
+ df = torch.tensor([3.0], dtype=DTYPE)
174
+ q = Mixture(
175
+ logits,
176
+ [
177
+ Independent(Normal(loc, ones), 1),
178
+ Independent(StudentT(df, loc, ones), 1),
179
+ ],
180
+ )
181
+ z = torch.randn(4, 1, dtype=DTYPE)
182
+ qd = q.detach()
183
+ assert torch.allclose(qd.log_prob(z), q.log_prob(z))
184
+ assert not qd.log_prob(z).requires_grad
185
+
186
+
187
+ # --------------------------------------------------------------------------
188
+ # ELBOObjective(stl=True)
189
+ # --------------------------------------------------------------------------
190
+ def test_stl_is_accepted_and_does_not_change_values(target):
191
+ params = make_params()
192
+ z = torch.randn(5, 1, dtype=DTYPE)
193
+ objective = ELBOObjective(target.log_prob, stl=False)
194
+ plain = objective.evaluate(make_q(*params), z)
195
+ stl = ELBOObjective(target.log_prob, stl=True).evaluate(make_q(*params), z)
196
+ assert torch.allclose(plain, stl)
197
+
198
+
199
+ def test_stl_drops_density_gradient_but_keeps_path_gradient(target):
200
+ params = make_params()
201
+ z = torch.randn(5, 1, dtype=DTYPE, requires_grad=True)
202
+
203
+ stl = ELBOObjective(target.log_prob, stl=True).evaluate(make_q(*params), z)
204
+ grads = torch.autograd.grad(stl.sum(), [z] + params, allow_unused=True)
205
+ assert grads[0].abs().sum() > 0
206
+ assert all(g is None for g in grads[1:])
207
+
208
+ objective = ELBOObjective(target.log_prob, stl=False)
209
+ plain = objective.evaluate(make_q(*params), z)
210
+ grads = torch.autograd.grad(plain.sum(), params, allow_unused=True)
211
+ assert all(g is not None and g.abs().sum() > 0 for g in grads)
212
+
213
+
214
+ def test_stl_objective_keeps_gradients_of_model_parameters():
215
+ phi = torch.tensor([0.5], dtype=DTYPE, requires_grad=True)
216
+ q = make_q(*make_params())
217
+ z = q.sample((8,))
218
+
219
+ def log_joint(x):
220
+ return Normal(phi, 1.0).log_prob(x).sum(-1)
221
+
222
+ value = ELBOObjective(log_joint, stl=True).evaluate(q, z)
223
+ (g,) = torch.autograd.grad(value.sum(), [phi])
224
+ assert g.abs().sum() > 0
225
+
226
+
227
+ def test_objective_shape_mismatch_still_raises():
228
+ q = make_q(*make_params())
229
+ objective = ELBOObjective(lambda z: z, stl=True) # shape (N, 1) vs (N,)
230
+ with pytest.raises(ValueError):
231
+ objective.evaluate(q, q.sample((4,)))
232
+
233
+
234
+ # --------------------------------------------------------------------------
235
+ # ScoreFunction with STL
236
+ # --------------------------------------------------------------------------
237
+ @pytest.mark.parametrize("stl", [False, True])
238
+ def test_estimate_returns_scalar_result_and_finite_gradients(target, stl):
239
+ params = make_params()
240
+ result = ScoreFunction(n_samples=8).estimate(
241
+ make_q(*params), ELBOObjective(target.log_prob, stl=stl)
242
+ )
243
+ assert isinstance(result, EstimateResult)
244
+ assert result.surrogate_loss.shape == () and result.value.shape == ()
245
+ assert not result.value.requires_grad
246
+ result.surrogate_loss.backward()
247
+ assert all(
248
+ p.grad is not None and torch.isfinite(p.grad).all() for p in params
249
+ )
250
+
251
+
252
+ def test_stl_surrogate_is_plain_reinforce_form(target):
253
+ """With STL the gradient is exactly mean((L - b) * grad log q)."""
254
+ params, n, baseline = make_params(), 16, 0.3
255
+
256
+ torch.manual_seed(11)
257
+ result = ScoreFunction(n_samples=n, baseline=baseline).estimate(
258
+ make_q(*params), ELBOObjective(target.log_prob, stl=True)
259
+ )
260
+ got = torch.autograd.grad(result.surrogate_loss, params)
261
+
262
+ torch.manual_seed(11)
263
+ q = make_q(*params)
264
+ z = q.sample(torch.Size([n]))
265
+ log_q = q.log_prob(z)
266
+ advantage = (target.log_prob(z) - log_q).detach() - baseline
267
+ expected = torch.autograd.grad(-(advantage * log_q).mean(), params)
268
+
269
+ for g, e in zip(got, expected):
270
+ assert torch.allclose(g, e)
271
+
272
+
273
+ def test_plain_surrogate_keeps_the_grad_l_term(target):
274
+ """Without STL the extra term -grad log q of the ELBO is present."""
275
+ params, n = make_params(), 16
276
+
277
+ torch.manual_seed(5)
278
+ result = ScoreFunction(n_samples=n).estimate(
279
+ make_q(*params), ELBOObjective(target.log_prob, stl=False)
280
+ )
281
+ got = torch.autograd.grad(result.surrogate_loss, params)
282
+
283
+ torch.manual_seed(5)
284
+ q = make_q(*params)
285
+ z = q.sample(torch.Size([n]))
286
+ log_q = q.log_prob(z)
287
+ values = target.log_prob(z) - log_q
288
+ surrogate = (values.detach() * log_q + values).mean()
289
+ expected = torch.autograd.grad(-surrogate, params)
290
+
291
+ for g, e in zip(got, expected):
292
+ assert torch.allclose(g, e)
293
+
294
+
295
+ def test_plain_equals_stl_with_baseline_shifted_by_one(target):
296
+ """For an ELBO grad L = -grad log q, so plain(b) equals STL(b + 1)."""
297
+ params, n, baseline = make_params(), 16, 0.3
298
+
299
+ def gradients(stl, b):
300
+ torch.manual_seed(21)
301
+ result = ScoreFunction(n_samples=n, baseline=b).estimate(
302
+ make_q(*params), ELBOObjective(target.log_prob, stl=stl)
303
+ )
304
+ return torch.autograd.grad(result.surrogate_loss, params)
305
+
306
+ plain = gradients(False, baseline)
307
+ shifted_stl = gradients(True, baseline + 1.0)
308
+ for g, e in zip(plain, shifted_stl):
309
+ assert torch.allclose(g, e)
310
+
311
+
312
+ @pytest.mark.parametrize("stl", [False, True], ids=["plain", "stl"])
313
+ @pytest.mark.parametrize("baseline", [0.0, -1.0], ids=["b0", "b-1"])
314
+ def test_score_function_is_unbiased(target, stl, baseline):
315
+ """The mean estimate matches the exact -ELBO gradient (quadrature)."""
316
+ torch.manual_seed(123)
317
+ params = make_params(seed=5)
318
+ exact = exact_neg_elbo_grad(params, target)
319
+ estimator = ScoreFunction(n_samples=64, baseline=baseline)
320
+ objective = ELBOObjective(target.log_prob, stl=stl)
321
+
322
+ n_repeats = 400
323
+ mean, var = gradient_moments(
324
+ lambda: estimator.estimate(make_q(*params), objective).surrogate_loss,
325
+ params,
326
+ n_repeats,
327
+ )
328
+ std_err = (var / n_repeats).sqrt()
329
+ # Five standard errors keep the statistical test from being flaky.
330
+ within = (mean - exact).abs() <= 5 * std_err + 1e-6
331
+ assert torch.all(within), (mean, exact, std_err)
332
+