Repository navigation
Add alpha to the existing stop-gradient decorator #285
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
60df4c8
6653398
459c54f
0ddddd5
e3284fd
d047257
fcc00c1
f718327
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -6,6 +6,7 @@ | |
| resampling. | ||
|
|
||
| See [Scibior and Wood (2021)](https://arxiv.org/abs/2106.10314) for more details. | ||
| For the discount, see [Tan et al.](https://arxiv.org/abs/2407.03085v2). | ||
| """ | ||
|
|
||
| from functools import wraps | ||
|
|
@@ -15,29 +16,43 @@ | |
|
|
||
| from cuthbertlib.resampling.protocols import Resampling | ||
| from cuthbertlib.resampling.utils import apply_resampling_indices | ||
| from cuthbertlib.types import Array, ArrayLike, ArrayTree, ArrayTreeLike | ||
| from cuthbertlib.types import ( | ||
| Array, | ||
| ArrayLike, | ||
| ArrayTree, | ||
| ArrayTreeLike, | ||
| ScalarArrayLike, | ||
| ) | ||
|
|
||
|
|
||
| def stop_gradient_decorator(func: Resampling) -> Resampling: | ||
| def stop_gradient_decorator( | ||
| func: Resampling, alpha: ScalarArrayLike = 1.0 | ||
| ) -> Resampling: | ||
| """Wrap a Resampling function to use stop gradient resampling. | ||
|
|
||
| Args: | ||
| func: A resampling function with signature | ||
| (key, logits, positions, n) -> (indices, logits_out, positions_out). | ||
| alpha: A scalar multiplier for the log-weight correction, clipped to [0, 1]. | ||
| The default, 1, preserves the original stop-gradient estimator; | ||
| 0 removes the correction. | ||
|
|
||
| Returns: | ||
| A Resampling function implementing stop gradient resampling. | ||
| """ | ||
| alpha = jnp.clip(jnp.broadcast_to(alpha, ()), 0, 1) | ||
| # Build a descriptive docstring that includes the wrapped function doc | ||
| wrapped_doc = func.__doc__ or "" | ||
| doc = f""" | ||
| Stop gradient resampling decorator. | ||
|
|
||
| This wrapper will call the provided resampling function, and then apply | ||
| the stop gradient trick of [Scibior and Wood (2021)](https://arxiv.org/abs/2106.10314). | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Don't forget to reference the paper
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I added the citation where the wrapper describes the discount. |
||
| Resulting estimates of the score function (i.e., the gradient of the | ||
| With alpha=1, resulting estimates of the score function (i.e., the gradient of the | ||
| log-likelihood with respect to model parameters) are unbiased, | ||
| corresponding to the classical Fisher estimate. | ||
| corresponding to the classical Fisher estimate. Values below 1 discount | ||
| the log-weight correction at resampling as in [Tan et al.](https://arxiv.org/abs/2407.03085v2). | ||
| With alpha=0, the correction is zero and gradients still pass through the selected particles. | ||
|
|
||
| Wrapped resampler documentation: | ||
| {wrapped_doc} | ||
|
|
@@ -51,11 +66,9 @@ def _wrapped( | |
| key, jax.lax.stop_gradient(logits), positions, n | ||
| ) | ||
|
|
||
| logits = jnp.asarray( | ||
| logits_base | ||
| + apply_resampling_indices(logits, idx_base) | ||
| - jax.lax.stop_gradient(apply_resampling_indices(logits, idx_base)) | ||
| ) | ||
| selected = apply_resampling_indices(logits, idx_base) | ||
| correction = alpha * (selected - jax.lax.stop_gradient(selected)) | ||
| logits = jnp.asarray(logits_base + correction) | ||
| return idx_base, logits, positions_base | ||
|
|
||
| # Attach the composed docstring and return a jitted version | ||
|
|
||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Main issue here is that you just didn't illustrate the new method at all. Ideally, the file should have been edited to show a similar figure, with the data and model here, as for Figure 1 in https://arxiv.org/abs/2407.03085v2
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I added a figure to the existing example showing how the bias and variance of the score estimates for
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can you make its background transparent please?
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Once done happy to approve
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Thanks, Adrien. I’ve updated the figure with a transparent background. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -140,6 +140,9 @@ resampling_fn = ( | |
| # In either case, do adaptive resampling | ||
| resampling_fn = adaptive.ess_decorator(resampling_fn, ess_threshold) | ||
| ``` | ||
|
|
||
| With the default `alpha=1`, Cuthbert applies the full gradient correction when it resamples. In [DMOP](https://arxiv.org/abs/2407.03085v2), `alpha` controls the bias–variance trade-off in the gradient estimates. | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @SamDuffield have we settled on how we do references? I don't think we have. I'm not a big fan of hyperlinks like these. TBC
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yeah we haven't got any unified approach to references. This is how we've been doing it in other examples so I'm fine with this here |
||
|
|
||
| Putting this together, we can define our PF MLL function. | ||
|
|
||
| ```{.python #pf_grad_bias-pf_mll} | ||
|
|
@@ -157,6 +160,7 @@ def pf_mll( | |
| m0, | ||
| chol_P0, | ||
| differentiable_resampling: bool, | ||
| alpha=1.0, | ||
| ): | ||
| """Bootstrap PF estimate of log p(y_{1:T} | theta).""" | ||
| log_q, log_r = theta | ||
|
|
@@ -178,7 +182,7 @@ def pf_mll( | |
| return logpdf(H @ x + d, ys[idx], chol_R, nan_support=False) | ||
|
|
||
| resampling_fn = ( | ||
| autodiff.stop_gradient_decorator(systematic.resampling) | ||
| autodiff.stop_gradient_decorator(systematic.resampling, alpha=alpha) | ||
| if differentiable_resampling | ||
| else systematic.resampling | ||
| ) | ||
|
|
@@ -348,7 +352,7 @@ key, *mc_keys = random.split(key, n_sims + 1) | |
|
|
||
| score_exact = kalman_grad(theta_true, ys, m0=m0, chol_P0=chol_P0) | ||
|
|
||
| def mc_scores_pf(diff: bool): | ||
| def mc_scores_pf(diff: bool, alpha=1.0): | ||
| out = [] | ||
| for k in mc_keys: | ||
| out.append( | ||
|
|
@@ -361,6 +365,7 @@ def mc_scores_pf(diff: bool): | |
| m0=m0, | ||
| chol_P0=chol_P0, | ||
| differentiable_resampling=diff, | ||
| alpha=alpha, | ||
| ) | ||
| ) | ||
| return jnp.stack(out, axis=0) | ||
|
|
@@ -437,6 +442,32 @@ Standard PF gives biased score estimates; the differentiable-resampling PF is mu | |
|
|
||
|  | ||
|
|
||
| We use the same 100 seeds to see how the bias and variance of each score estimate change with `alpha`. | ||
|
|
||
| ??? "Code to plot score error against alpha." | ||
| ```{.python #pf_grad_bias-discount} | ||
| alphas = [0.0, 0.25, 0.5, 0.75, 0.9, 0.97, 1.0] | ||
| scores_by_alpha = jnp.stack( | ||
| [score_pf_dpf if alpha == 1.0 else mc_scores_pf(True, alpha) for alpha in alphas] | ||
| ) | ||
| errors = scores_by_alpha - score_exact | ||
| mse = jnp.mean(errors**2, axis=1) | ||
| squared_bias = jnp.mean(errors, axis=1)**2 | ||
| variance = jnp.var(scores_by_alpha, axis=1) | ||
|
|
||
| fig, axes = plt.subplots(1, 2, figsize=(9, 3.6), layout="constrained") | ||
| for j, (ax, parameter) in enumerate(zip(axes, [r"$\log q$", r"$\log r$"])): | ||
| ax.semilogy(alphas, mse[:, j], "o-", label="Mean squared error") | ||
| ax.semilogy(alphas, squared_bias[:, j], "s--", label="Squared bias") | ||
| ax.semilogy(alphas, variance[:, j], "^:", label="Variance") | ||
| ax.set(xlabel=r"Discount $\alpha$", title=f"Score for {parameter}") | ||
| axes[0].set_ylabel("Squared score error") | ||
| axes[0].legend() | ||
| fig.savefig("docs/assets/pf_grad_bias_discount.png", dpi=200, transparent=True) | ||
| ``` | ||
|
|
||
|  | ||
|
|
||
| One important aspect in practice is efficiency. We now compare the time it takes to run a backwards pass over the differentiable and non-differentiable variants of the filter. | ||
|
|
||
| ```{.python #pf_grad_bias-timing} | ||
|
|
@@ -601,6 +632,7 @@ Finally, we should be sure that the forward pass is not actually being modified | |
| <<pf_grad_bias-plot_slices>> | ||
| <<pf_grad_bias-mc_bias>> | ||
| <<pf_grad_bias-boxplots>> | ||
| <<pf_grad_bias-discount>> | ||
| <<pf_grad_bias-timing>> | ||
| <<pf_grad_bias-final_particles>> | ||
| ``` | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -156,3 +156,39 @@ def resampled_lse(sigma, resampling_fn): | |
| )(true_sigma) | ||
|
|
||
| chex.assert_trees_all_close(grad_stop, grad_base, rtol=0.05, atol=0.05) | ||
|
|
||
| @parameterized.parameters(None, 0.0, 0.5, 1.0, {"alpha": jnp.array(0.5)}) | ||
| def test_stop_gradient_discount(self, alpha): | ||
| base = systematic.resampling | ||
| if alpha is None: | ||
| resample = stop_gradient_decorator(base) | ||
| alpha = 1.0 | ||
| else: | ||
| resample = stop_gradient_decorator(base, alpha=alpha) | ||
|
|
||
| key = random.key(42) | ||
| logits, xs = jnp.array([-2.0, 0.0, 1.0]), jnp.arange(3.0) | ||
| expected = base(key, logits, xs, 3) | ||
| chex.assert_trees_all_equal(resample(key, logits, xs, 3), expected) | ||
|
|
||
| selected = jnp.eye(3)[expected[0]] | ||
| dw = jax.jacrev(lambda w: resample(key, w, xs, 3)[1])(logits) | ||
| dx = jax.jacrev(lambda x: resample(key, logits, x, 3)[2])(xs) | ||
| chex.assert_trees_all_equal(dw, alpha * selected) | ||
| chex.assert_trees_all_equal(dx, selected) | ||
|
|
||
| def test_compiled_discount(self): | ||
| key = random.key(42) | ||
| logits, xs = jnp.array([-2.0, 0.0, 1.0]), jnp.arange(3.0) | ||
| indices, _, _ = systematic.resampling(key, logits, xs, 3) | ||
| selected = jnp.eye(3)[indices] | ||
|
|
||
| @jax.jit | ||
| def jacobian(alpha): | ||
| resample = stop_gradient_decorator(systematic.resampling, alpha=alpha) | ||
| return jax.jacrev(lambda w: resample(key, w, xs, 3)[1])(logits) | ||
|
|
||
| for alpha, expected in [(-0.1, 0.0), (0.5, 0.5), (1.1, 1.0)]: | ||
| chex.assert_trees_all_equal(jacobian(alpha), expected * selected) | ||
| with self.assertRaises(ValueError): | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This would fail to raise for compiled code.
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. or maybe it would but for the wrong reason. See comment there
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I replaced that test with a |
||
| jacobian(jnp.ones(3)) | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Probably add the reference here too
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I added the Tan et al. reference to the module docstring.