diff --git a/cuthbertlib/resampling/autodiff.py b/cuthbertlib/resampling/autodiff.py index 9b303189..ca1d9a50 100644 --- a/cuthbertlib/resampling/autodiff.py +++ b/cuthbertlib/resampling/autodiff.py @@ -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,19 +16,31 @@ 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""" @@ -35,9 +48,11 @@ def stop_gradient_decorator(func: Resampling) -> Resampling: 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). - 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 diff --git a/docs/assets/pf_grad_bias_discount.png b/docs/assets/pf_grad_bias_discount.png new file mode 100644 index 00000000..68b4b9c7 Binary files /dev/null and b/docs/assets/pf_grad_bias_discount.png differ diff --git a/docs/examples/diff_pf_resampling.md b/docs/examples/diff_pf_resampling.md index 51ab48cb..0a628c73 100644 --- a/docs/examples/diff_pf_resampling.md +++ b/docs/examples/diff_pf_resampling.md @@ -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. + 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 ![Score estimates across seeds](../assets/pf_grad_bias_score_boxplots.png) +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) + ``` + +![Mean squared error, squared bias and variance of the two score estimates relative to the Kalman score](../assets/pf_grad_bias_discount.png) + 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 <> <> <> +<> <> <> ``` diff --git a/tests/cuthbertlib/resampling/test_resamplings.py b/tests/cuthbertlib/resampling/test_resamplings.py index 04998078..4d110ca5 100644 --- a/tests/cuthbertlib/resampling/test_resamplings.py +++ b/tests/cuthbertlib/resampling/test_resamplings.py @@ -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): + jacobian(jnp.ones(3))